smtpap.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. /**
  2. * smtpap.c
  3. * SMTP Application Proxy for Onion Routing
  4. *
  5. * Matej Pfajfar <mp292@cam.ac.uk>
  6. */
  7. /*
  8. * Changes :
  9. * $Log$
  10. * Revision 1.1 2002/06/26 22:45:50 arma
  11. * Initial revision
  12. *
  13. * Revision 1.32 2002/04/02 14:29:49 badbytes
  14. * Final finishes.
  15. *
  16. * Revision 1.31 2002/03/25 08:03:17 badbytes
  17. * Added header sanitization.
  18. *
  19. * Revision 1.30 2002/03/02 23:54:06 mp292
  20. * Fixed missing CRLFs at the end of error messages.
  21. *
  22. * Revision 1.29 2002/01/29 01:00:10 mp292
  23. * All network operations are now timeoutable.
  24. *
  25. * Revision 1.28 2002/01/28 21:38:18 mp292
  26. * Fixed bugs in RSET handling. Added Anonimize option which signifies whether
  27. * the router should falsify the identity of the sender or not.
  28. *
  29. * Revision 1.27 2002/01/26 22:45:02 mp292
  30. * Now handles SS_ERROR_INVALID_PORT.
  31. *
  32. * Revision 1.26 2002/01/26 22:33:21 mp292
  33. * Removed hard-coded values for onion proxy return codes. Also fixed a bug in
  34. * parameter checking.
  35. *
  36. * Revision 1.25 2002/01/26 21:58:27 mp292
  37. * Added some missing parameter checking.
  38. *
  39. * Revision 1.24 2002/01/26 21:50:17 mp292
  40. * Reviewed according to Secure-Programs-HOWTO. Still need to deal with network
  41. * timeouts.
  42. *
  43. * Revision 1.23 2002/01/18 21:07:02 mp292
  44. * (a) THe form of HELO is now HELO Anonymous.Smtp.Daemon rather than the real
  45. * address. (b) The user *can* now specify a default SMTP daemon to route through
  46. * although this is insecure and not recommended.
  47. *
  48. * Revision 1.22 2002/01/16 23:01:58 mp292
  49. * First phase of system testing completed (main functionality).
  50. *
  51. * Revision 1.21 2002/01/16 17:04:01 mp292
  52. * Bug in checking whether incoming connection is local or not.
  53. *
  54. * Revision 1.20 2002/01/09 09:18:22 badbytes
  55. * Now handles EINTR error from accept().
  56. *
  57. * Revision 1.19 2001/12/19 11:15:27 badbytes
  58. * Corrected AF_INET to PF_INET in socket() calls.
  59. *
  60. * Revision 1.18 2001/12/19 08:36:04 badbytes
  61. * Incorrect error checking in recv() calls caused zombies ... fixed
  62. *
  63. * Revision 1.17 2001/12/18 14:42:46 badbytes
  64. * Variable name op_port_str was incorrectly named, changed to dest_port_str
  65. *
  66. * Revision 1.16 2001/12/18 13:20:16 badbytes
  67. * Some error messages did not include a terminating <CRLF>
  68. *
  69. * Revision 1.15 2001/12/18 12:37:23 badbytes
  70. * Found an overflow bug ...
  71. *
  72. * Revision 1.14 2001/12/18 09:17:31 badbytes
  73. * Corrected a spelling mistake in print_usage()
  74. *
  75. * Revision 1.13 2001/12/14 13:13:24 badbytes
  76. * Changed types.h references to ss.h
  77. *
  78. * Revision 1.12 2001/12/14 09:17:25 badbytes
  79. * Moved function stolower(char *str) from smtpap.c to common/utils.c
  80. *
  81. * Revision 1.11 2001/12/13 13:51:05 badbytes
  82. * Fixed a bug in processing command-line parameters.
  83. *
  84. * Revision 1.10 2001/12/13 13:36:44 badbytes
  85. * Now accepts the -l command-line option which specifies the logging threshold.
  86. *
  87. * Revision 1.9 2001/12/12 16:02:29 badbytes
  88. * Testing completed.
  89. *
  90. * Revision 1.8 2001/12/11 16:30:20 badbytes
  91. * Some bugs removed, still testing though.
  92. *
  93. * Revision 1.7 2001/12/11 14:12:20 badbytes
  94. * Onion Proxy connection setup completed. Proceeding to test.
  95. *
  96. * Revision 1.6 2001/12/11 10:43:21 badbytes
  97. * MAIL and RCPT handling completed. Still coding connection to Onion Proxy.
  98. *
  99. * Revision 1.5 2001/12/10 16:10:35 badbytes
  100. * Wrote a tokenize() function to help with parsing input from SMTP clients.
  101. *
  102. * Revision 1.4 2001/12/07 15:02:43 badbytes
  103. * Server setup code completed.
  104. *
  105. */
  106. #include <sys/types.h>
  107. #include <sys/socket.h>
  108. #include <sys/time.h>
  109. #include <netinet/in.h>
  110. #include <netdb.h>
  111. #include <arpa/inet.h>
  112. #include <errno.h>
  113. #include <ctype.h>
  114. #include <stdio.h>
  115. #include <unistd.h>
  116. #include <signal.h>
  117. #include <wait.h>
  118. #include <stdarg.h>
  119. #include <ctype.h>
  120. #include <stdint.h>
  121. #include <string.h>
  122. #include <stdlib.h>
  123. #include <time.h>
  124. #include "../common/log.h"
  125. #include "../common/config.h"
  126. #include "../common/ss.h"
  127. #include "../common/utils.h"
  128. #include "../common/version.h"
  129. #include "smtpap.h"
  130. #include "io.h"
  131. int loglevel = LOG_ERR;
  132. struct timeval conn_tout;
  133. struct timeval *conn_toutp = &conn_tout;
  134. /* valid command-line options */
  135. static const char *args = "hf:p:l:";
  136. /* valid config file options */
  137. static config_opt_t options[] =
  138. {
  139. {"OnionProxy", CONFIG_TYPE_INT, {0}, 0},
  140. {"MaxConn", CONFIG_TYPE_INT, {0}, 0},
  141. {"Anonimize", CONFIG_TYPE_INT, {0}, 0},
  142. {"ConnTimeout", CONFIG_TYPE_INT, {0}, 0},
  143. {0}
  144. };
  145. enum opts {
  146. OnionProxy=0,MaxConn, Anonimize, ConnTimeout
  147. };
  148. /* number of open connections */
  149. int connections=0;
  150. /* prints help on using smtpap */
  151. void print_usage()
  152. {
  153. char *program = "smtpap";
  154. printf("\n%s - SMTP application proxy for Onion Routing.\nUsage : %s -f config [-p port -l loglevel -h]\n-h : display this help\n-f config : config file\n-p port : port number which %s should bind to\n-l loglevel : logging threshold; one of alert|crit|err|warning|notice|info|debug\n\n", program,program,program);
  155. }
  156. /* used for reaping zombie processes */
  157. void sigchld_handler(int s)
  158. {
  159. while (wait(NULL) > 0);
  160. connections--;
  161. }
  162. /* takes the contents of a RCPT command in a null-terminated string and retrieves the address
  163. * of the corresponding recipient domain*/
  164. char *extract_smtp_dest(char *rcptbuf)
  165. {
  166. char *dest_smtp=NULL;
  167. char *pos1, *pos2;
  168. if (!rcptbuf)
  169. return NULL;
  170. pos1 = (char *)strchr(rcptbuf,'@');
  171. if (pos1 == NULL)
  172. return NULL;
  173. pos2 = (char *)strpbrk(pos1,SMTPAP_PATH_SEPCHARS);
  174. if (pos2 == NULL)
  175. return NULL;
  176. else
  177. {
  178. dest_smtp = (char *)malloc((size_t)(pos2-pos1));
  179. if (!dest_smtp)
  180. {
  181. log(LOG_ERR,"Could not allocate memory.");
  182. return NULL;
  183. }
  184. else
  185. {
  186. strncpy(dest_smtp,pos1+1,(size_t)(pos2-pos1-1));
  187. dest_smtp[pos2-pos1-1] = 0;
  188. }
  189. }
  190. return dest_smtp;
  191. }
  192. /* process a DATA stream and remove any e-mail headers */
  193. int sanitize_data(unsigned char **buf, int *buflen)
  194. {
  195. unsigned char *offset; /* offset to data after the last header */
  196. unsigned char *crlf = NULL;
  197. unsigned char *colon = NULL;
  198. unsigned char *line;
  199. unsigned char *newbuf;
  200. int newbuflen;
  201. if ((!buf) || (!buflen)) /* invalid parameters */
  202. return -1;
  203. offset = *buf;
  204. line = *buf;
  205. /* process the data line by line and discard anything that looks like a header */
  206. while(1)
  207. {
  208. /* find the end of line */
  209. crlf = strstr(line, SMTPAP_CRLF);
  210. if (crlf)
  211. {
  212. colon = (unsigned char *)memchr((void *)line,(int)':',crlf-line);
  213. if (!colon)
  214. break; /* this doesn't seem to be a header, can stop */
  215. else
  216. offset = crlf + 2; /* discard this line */
  217. line = crlf + 2; /* move on to the next line */
  218. }
  219. else /* no more CRLFs found, end of data */
  220. /* NB : there is no need to check the current line at this stage as this will be of the form <CRLF>.<CRLF> */
  221. /* we should never reach this point in the code anyway, the '.' will be trapped as a non-header line in the above code */
  222. break;
  223. }
  224. if (offset != *buf) /* data changed */
  225. {
  226. newbuflen = *buflen - (offset - *buf);
  227. newbuf = (unsigned char *)malloc(newbuflen+1); /* leave space for a terminating NULL character */
  228. if (!newbuf) /* malloc() error */
  229. return -1;
  230. else
  231. {
  232. /* copy into the new buffer */
  233. memcpy((void *)newbuf, (void *)offset, newbuflen);
  234. newbuf[newbuflen] = 0;
  235. /* replace the old buffer with the new one */
  236. free((void *)*buf);
  237. *buf = newbuf;
  238. *buflen = newbuflen;
  239. }
  240. }
  241. return 0;
  242. }
  243. /* main logic of smtpap */
  244. int handle_connection(int s, struct hostent *local, struct sockaddr_in remote, u_short op_port)
  245. {
  246. int retval = 0;
  247. int state = 0; /* 0 - start / RSET received
  248. * 1 - connection not local, waiting for QUIT
  249. * 2 - connection local, waiting for HELO/EHLO
  250. * 3 - HELO/EHLO received, waiting for MAIL
  251. * 4 - MAIL received, waiting for RCPT
  252. * 5 - waiting for DATA
  253. * 6 - DATA received, accepting data
  254. * - data accepted, back to state 3
  255. */
  256. int islocal = 0;
  257. char *cp;
  258. int i=0;
  259. char message[512]; /* for storing outgoing messages */
  260. char *inbuf = NULL; /* for storing incoming messages */
  261. char *token = NULL; /* next token in the incoming message */
  262. char *tmpbuf = NULL; /* temporary buffer for copying data */
  263. char *mailbuf = NULL; /* storing the MAIL command */
  264. char **rcptarray = NULL; /* storing a NULL-terminated array of RCPT commands */
  265. char *rcptbuf = NULL; /* storing a single RCPT command */
  266. int tmpbuflen = 0; /* length of tmpbuflen in bytes */
  267. int inbuflen = 0; /* length of inbuf in bytes */
  268. int inputlen = 0; /* length of actual input in bytes */
  269. int mailbuflen=0; /* etc ... */
  270. int rcptbuflen=0;
  271. int inputerror=0; /* error occured when receiving data from the client */
  272. /* the following is used for conecting to the SMTP host through the OR network */
  273. char *dest_addr_str = NULL; /* for storing the ASCII address of the destination SMTP */
  274. int sop=-1; /* socket for connecting to the onion proxy */
  275. struct sockaddr_in op_addr; /* stores the address of the onion proxy */
  276. ss_t ss; /* standard structure */
  277. char dest_port_str[6]; /* ascii representation of the destination port */
  278. /* input and output buffers for talking to the onion proxy */
  279. char *op_out = NULL;
  280. char *op_in = NULL;
  281. int op_outlen = 0;
  282. int op_inlen = 0;
  283. int partial_dataend = 0; /* used for recognising the <CRLF>.<CRLF> sequence that ends the DATA segment */
  284. if (!local)
  285. return -1;
  286. log(LOG_DEBUG, "handle_connection() : Local address = %s.", inet_ntoa(*(struct in_addr *)local->h_addr));
  287. log(LOG_DEBUG, "handle_connection() : Remote address = %s.", inet_ntoa(remote.sin_addr));
  288. /* first check that the connection is from the local host, otherwise reject */
  289. if (*(uint32_t *)&remote.sin_addr == inet_addr("127.0.0.1"))
  290. islocal = 1;
  291. for (i=0; (local->h_addr_list[i] != NULL) && (!islocal); i++)
  292. {
  293. cp = local->h_addr_list[i];
  294. log(LOG_DEBUG,"handle_connection() : Checking if connection is from address %s.",inet_ntoa(*(struct in_addr *)cp));
  295. if (!memcmp(&remote.sin_addr, cp, sizeof(struct in_addr)))
  296. islocal = 1;
  297. }
  298. if (islocal)
  299. {
  300. log(LOG_DEBUG,"handle_connection() : Connection seems to be local. Will accept.");
  301. state = 2;
  302. sendmessage(s, (char *)message, (size_t)512, "220 This is smtpap v1.0 running on %s.%s",local->h_name,SMTPAP_CRLF);
  303. }
  304. else
  305. {
  306. log(LOG_DEBUG,"handle_connection() : Connection doesn't seem to be local. Will reject.");
  307. state = 1;
  308. sendmessage(s,(char *)message, (size_t)512,"554 smtpap v1.0 Connection refused. Only local connections allowed.%s",SMTPAP_CRLF);
  309. }
  310. /* initially allocate 512 bytes for incoming message buffer */
  311. inbuf = (char *)malloc((size_t)512);
  312. if (!inbuf)
  313. {
  314. log(LOG_ERR,"Could not allocate memory.");
  315. return -1;
  316. }
  317. inbuflen = 512;
  318. /* initially allocate 512 bytes for the temporary buffer */
  319. tmpbuf = (char *)malloc((size_t)512);
  320. if (!tmpbuf)
  321. {
  322. log(LOG_ERR,"Could not allocate memory.");
  323. free(inbuf);
  324. return -1;
  325. }
  326. tmpbuflen = 512;
  327. while(1)
  328. {
  329. inputlen = 0;
  330. do
  331. {
  332. if (inputlen == inbuflen-1) /* we need to increase the buffer size */
  333. {
  334. /* increase the size of the buffers */
  335. inbuflen += 512;
  336. tmpbuflen += 512;
  337. inbuf = (char *)realloc(inbuf,(size_t)inbuflen);
  338. if (!inbuf)
  339. {
  340. log(LOG_ERR,"Could not allocate memory.");
  341. inputerror = 1;
  342. break;
  343. }
  344. tmpbuf = (char *)realloc(tmpbuf,(size_t)tmpbuflen);
  345. if (!tmpbuf)
  346. {
  347. log(LOG_ERR,"Could not allocate memory.");
  348. free(inbuf);
  349. inputerror = 1;
  350. break;
  351. }
  352. }
  353. retval=read_tout(s,inbuf+inputlen,(size_t)(inbuflen-inputlen-1),0, conn_toutp); /* subtract 1 from inbuflen to leave space for \0 */
  354. if (retval <= 0)
  355. {
  356. log(LOG_ERR,"Error occured while receiving data.");
  357. inputerror = 1;
  358. break;
  359. }
  360. else
  361. {
  362. inputerror = 0;
  363. inputlen += retval;
  364. /* exit clause if we have received CRLF or SMTPAP_ENDDATA, otherwise we need to keep reading*/
  365. if ( (state == 6) && (inputlen >= SMTPAP_ENDDATA_LEN) )
  366. {
  367. if (!strncmp(inbuf+inputlen-SMTPAP_ENDDATA_LEN,SMTPAP_ENDDATA,SMTPAP_ENDDATA_LEN))
  368. break;
  369. }
  370. else if ( (state != 6) && (inputlen >= SMTPAP_CRLF_LEN) )
  371. {
  372. if (!strncmp(inbuf+inputlen-SMTPAP_CRLF_LEN,SMTPAP_CRLF,SMTPAP_CRLF_LEN))
  373. break;
  374. }
  375. }
  376. } while(1);
  377. if (inputerror != 0)
  378. break;
  379. if (*inbuf == EOF)
  380. {
  381. log(LOG_DEBUG,"handle_connection() : Received EOF. Exiting.");
  382. break;
  383. }
  384. inbuf[inputlen]=0; /* add the terminating NULL character */
  385. log(LOG_DEBUG, "Received this from client : %s",inbuf);
  386. /* save a copy of inbuf into tmpbuf, because calls to strtok() will change it */
  387. strcpy(tmpbuf,inbuf);
  388. /* now handle input depending on the state */
  389. /* first check for a quit */
  390. token = stolower((char *)strtok(inbuf,SMTPAP_SEPCHARS));
  391. log(LOG_DEBUG,"handle_connection() : First token is %s.",token);
  392. if ((!strcmp(token,SMTPAP_QUIT)) && (state != 6)) /* QUIT command - but doesn't count in state 6
  393. * That's when we are receiving DATA input
  394. */
  395. {
  396. sendmessage(s,(char *)message, (size_t)512,"221 %s closing connection. Goodbye.%s",local->h_name,SMTPAP_CRLF);
  397. break;
  398. }
  399. /* check for a RSET */
  400. if ((!strcmp(token,SMTPAP_RSET)) && (state !=6)) /* RSET command - again, doesn't count in state 6 */
  401. {
  402. sendmessage(s,(char *)message,(size_t)512,"250 RSET received.%s",SMTPAP_CRLF);
  403. /* clean up message state */
  404. if (mailbuf != NULL)
  405. {
  406. free(mailbuf);
  407. mailbuf = NULL;
  408. }
  409. if (rcptarray != NULL)
  410. {
  411. free(rcptarray);
  412. rcptarray = NULL;
  413. }
  414. if (rcptbuf != NULL)
  415. {
  416. free(rcptbuf);
  417. rcptbuf=NULL;
  418. }
  419. close(sop);
  420. /* set state to 2/3 (depending on wether we have recieved HELO yet) and loop back and start again */
  421. if (state != 2)
  422. state=3;
  423. continue;
  424. }
  425. if (state == 1)
  426. {
  427. sendmessage(s,(char *)message, (size_t)512,"503 Connection refused. Please QUIT.%s",SMTPAP_CRLF);
  428. }
  429. else if (state == 2)
  430. {
  431. if ((!strcmp(token,SMTPAP_HELO)) || (!strcmp(token,SMTPAP_EHLO)))
  432. {
  433. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  434. if (!token) /* no more tokens in inbuf */
  435. {
  436. log(LOG_DEBUG,"handle_connection() : handle_connection : Received HELO/EHLO without arguments.");
  437. sendmessage(s,(char *)message,(size_t)512,"500 HELO/EHLO requires domain address.%s",SMTPAP_CRLF);
  438. }
  439. else
  440. {
  441. log(LOG_DEBUG,"handle_connection() : handle_connection : Received HELO/EHLO with the following domain address : %s.",token);
  442. state =3;
  443. sendmessage(s,(char *)message,(size_t)512,"250 Hello user at %s. Pleased to meet you.%s",inet_ntoa(remote.sin_addr),SMTPAP_CRLF);
  444. }
  445. }
  446. else
  447. sendmessage(s,(char *)message,(size_t)512,"503 Expecting either HELO/EHLO or QUIT.%s",SMTPAP_CRLF);
  448. }
  449. else if (state == 3)
  450. {
  451. int further_check=0;
  452. if ((!strncmp(token,SMTPAP_MAIL,SMTPAP_MAIL_LEN)))
  453. {
  454. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  455. if (!token)
  456. {
  457. sendmessage(s,(char *)message,(size_t)512,"500 MAIL requires From:<sender@address> .%s",SMTPAP_CRLF);
  458. }
  459. else
  460. {
  461. stolower(token);
  462. if (!strcmp(token,"from:")) /* from: separate from the address */
  463. {
  464. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  465. if (token == NULL) /* expected another parameter but it's not there */
  466. {
  467. log(LOG_DEBUG,"handle_connection() : Received MAIL From: without an address.");
  468. sendmessage(s,(char *)message,(size_t)512,"500 MAIL From: requires sender address.%s",SMTPAP_CRLF);
  469. further_check = 0;
  470. }
  471. else /* continue further checking */
  472. further_check = 1;
  473. }
  474. else if (!strcmp(token,"from")) /* probably from : address */
  475. {
  476. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  477. if (token == NULL) /* not enough parameters */
  478. {
  479. log(LOG_DEBUG,"handle_connection() : Received Mail From with no other parameters.");
  480. sendmessage(s,(char *)message,(size_t)512, "500 MAIL From: requires sender address.%s",SMTPAP_CRLF);
  481. further_check=0;
  482. }
  483. else if ( (token[0] == ':') && (token[1]!='\0') ) /* contains :address */
  484. {
  485. token++;
  486. further_check=1;
  487. }
  488. else if ( (token[0] == ':') && (token[1]=='\0') )/* the address is in the next token */
  489. {
  490. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  491. if (token == NULL) /* not enough parameters */
  492. {
  493. log(LOG_DEBUG,"handle_connection() : Received Mail From : with no other parameters.");
  494. sendmessage(s,(char *)message,(size_t)512,"500 MAIL From: requires sender address.%s",SMTPAP_CRLF);
  495. further_check = 0;
  496. }
  497. else /* continue further checking */
  498. further_check =1;
  499. }
  500. else /* couldn't find a colon (:) */
  501. {
  502. log(LOG_DEBUG,"handle_connection() : Couldn't find a colon in the received MAIL command.");
  503. sendmessage(s,(char *)message,(size_t)512,"500 There is a colon (:) missing in that command.%s",SMTPAP_CRLF);
  504. further_check = 1;
  505. }
  506. }
  507. else /* probably from:address */
  508. {
  509. if (!strncmp(token,"from:",5)) /* string starts with from: */
  510. {
  511. token += 5; /* skip the from: bit */
  512. further_check = 1; /* continue further checking */
  513. }
  514. else /* error */
  515. {
  516. log(LOG_DEBUG,"handle_connection() : MAIL parameters don't start with from: .");
  517. sendmessage(s,(char *)message,(size_t)512,"500 MAIL requires From:<sender@address>.%s",SMTPAP_CRLF);
  518. further_check=0;
  519. }
  520. }
  521. if (further_check == 1) /* check that this is in the correct, format - we can't handle anything else
  522. * but straightforward <user@host> representation, <> optional
  523. */
  524. {
  525. if (((cp = (char *)strchr(token,',')) != NULL) || ((cp = (char *)strchr(token,':')) != NULL)) /* path contains , or : - can't cope with that */
  526. {
  527. log(LOG_DEBUG,"handle_connection() : The client is probably trying to specify a reverse path, which I can't handle.");
  528. sendmessage(s,(char *)message,(size_t)512,"500 I can only handle a simple return address.%s",SMTPAP_CRLF);
  529. }
  530. else if ((cp = (char *)strchr(token,'@')) == NULL) /* no @, that is most likely a problem :-) */
  531. {
  532. log(LOG_DEBUG,"handle_connection() : The client specified a sender address with no @.");
  533. sendmessage(s,(char *)message,(size_t)512,"500 Domain name required.%s",SMTPAP_CRLF);
  534. }
  535. else /* the mail command seems to be OK, save it */
  536. {
  537. if (mailbuf != NULL)
  538. free(mailbuf);
  539. mailbuflen = strlen(tmpbuf) + 1;
  540. mailbuf = (char *)malloc(mailbuflen);
  541. if (!mailbuf)
  542. {
  543. log(LOG_ERR,"Could not allocate memory.");
  544. sendmessage(s,(char *)message,(size_t)512,"451 Insufficient memory.%s",SMTPAP_CRLF);
  545. }
  546. else
  547. {
  548. strncpy(mailbuf,tmpbuf,mailbuflen);
  549. mailbuf[mailbuflen-1] = '\0'; /* add the terminating NULL character */
  550. log(LOG_DEBUG,"handle_connection() : MAIL command saved as %s.",mailbuf);
  551. /* send an OK response to the client */
  552. sendmessage(s,(char *)message,(size_t)512,"250 Sender address OK.%s",SMTPAP_CRLF);
  553. state=4;
  554. }
  555. }
  556. }
  557. }
  558. }
  559. else
  560. sendmessage(s,(char *)message, (size_t)512,"503 Need MAIL first.%s",SMTPAP_CRLF);
  561. }
  562. else if(state == 4)
  563. {
  564. int further_check=0;
  565. if ((!strcmp(token,SMTPAP_RCPT)))
  566. {
  567. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  568. if (!token)
  569. {
  570. sendmessage(s,(char *)message,(size_t)512,"500 RCPT requires To:<recipient@address> .%s",SMTPAP_CRLF);
  571. }
  572. else
  573. {
  574. stolower(token);
  575. if (!strcmp(token,"to:")) /* to: separate from the address */
  576. {
  577. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  578. if (token == NULL) /* expected another parameter but it's not there */
  579. {
  580. log(LOG_DEBUG,"handle_connection() : Received RCPT To: without an address.");
  581. sendmessage(s,(char *)message,(size_t)512,"500 RCPT To: requires recipient address.%s",SMTPAP_CRLF);
  582. further_check = 0;
  583. }
  584. else /* continue further checking */
  585. further_check = 1;
  586. }
  587. else if (!strcmp(token,"to")) /* probably to : address or to :address */
  588. {
  589. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  590. if (token == NULL) /* not enough parameters */
  591. {
  592. log(LOG_DEBUG,"handle_connection() : Received RCPT To with no other parameters.");
  593. sendmessage(s,(char *)message,(size_t)512, "500 RCPT To: requires recipient address.%s",SMTPAP_CRLF);
  594. further_check=0;
  595. }
  596. else if ( (token[0] == ':') && (token[1]!='\0') ) /* contains :address */
  597. {
  598. token++;
  599. further_check=1;
  600. }
  601. else if ( (token[0] == ':') && (token[1]=='\0') )/* the address is in the next token */
  602. {
  603. token = (char *)strtok(NULL,SMTPAP_SEPCHARS);
  604. if (token == NULL) /* not enough parameters */
  605. {
  606. log(LOG_DEBUG,"handle_connection() : Received RCPT To : with no other parameters.");
  607. sendmessage(s,(char *)message,(size_t)512,"500 RCPT To: requires recipient address.%s",SMTPAP_CRLF);
  608. further_check = 0;
  609. }
  610. else /* continue further checking */
  611. further_check =1;
  612. }
  613. else /* couldn't find a colon (:) */
  614. {
  615. log(LOG_DEBUG,"handle_connection() : Couldn't find a colon in the received RCPT command.");
  616. sendmessage(s,(char *)message,(size_t)512,"500 There is a colon (:) missing in that command.%s",SMTPAP_CRLF);
  617. further_check = 1;
  618. }
  619. }
  620. else /* probably to:address */
  621. {
  622. if (!strncmp(token,"to:",3)) /* string starts with from: */
  623. {
  624. token += 3; /* skip the to: bit */
  625. further_check = 1; /* continue further checking */
  626. }
  627. else /* error */
  628. {
  629. log(LOG_DEBUG,"handle_connection() : RCPT parameters don't start with to: .");
  630. sendmessage(s,(char *)message,(size_t)512,"500 RCPT requires To:<recipient@address>.%s",SMTPAP_CRLF);
  631. further_check=0;
  632. }
  633. }
  634. if (further_check == 1) /* check that this is in the correct, format - we can't handle anything else
  635. * but straightforward <user@host> representation, <> optional
  636. */
  637. {
  638. if (((cp = (char *)strchr(token,',')) != NULL) || ((cp = (char *)strchr(token,':')) != NULL)) /* path contains , or : - can't cope with that */
  639. {
  640. log(LOG_DEBUG,"handle_connection() : The client is probably trying to specify a forward path, which I can't handle.");
  641. sendmessage(s,(char *)message,(size_t)512,"500 I can only handle a simple recipient address.%s",SMTPAP_CRLF);
  642. }
  643. else if ((cp = (char *)strchr(token,'@')) == NULL) /* no @, that is most likely a problem :-) */
  644. {
  645. log(LOG_DEBUG,"handle_connection() : The client specified a recipient address with no @.");
  646. sendmessage(s,(char *)message,(size_t)512,"500 Domain name required.%s",SMTPAP_CRLF);
  647. }
  648. else /* the rcpt command seems to be OK, save it */
  649. {
  650. if (rcptbuf != NULL)
  651. {
  652. free(rcptbuf);
  653. rcptbuf = NULL;
  654. }
  655. rcptbuflen = strlen(tmpbuf) + 1;
  656. rcptbuf = (char *)malloc(rcptbuflen);
  657. if (!rcptbuf)
  658. {
  659. log(LOG_ERR,"Could not allocate memory.");
  660. sendmessage(s,(char *)message,(size_t)512,"451 Insufficient memory.%s",SMTPAP_CRLF);
  661. }
  662. else
  663. {
  664. strncpy(rcptbuf,tmpbuf,rcptbuflen);
  665. rcptbuf[rcptbuflen-1] = '\0'; /* add the terminating NULL character */
  666. log(LOG_DEBUG,"handle_connection() : handle_connection : RCPT command saved.");
  667. /* attempt to connect to the destination SMTP server through the OR network */
  668. /* first extract the destination address */
  669. dest_addr_str = extract_smtp_dest(rcptbuf);
  670. log(LOG_DEBUG,"handle_connection() : handle_connection : called extract_smtp_dest()");
  671. if (!dest_addr_str)
  672. {
  673. log(LOG_DEBUG,"handle_connection() : Could not extract a destination SMTP address from the specified recipient address.");
  674. sendmessage(s,(char *)message,(size_t)512,"550 Could not extract destination domain.%s",SMTPAP_CRLF);
  675. }
  676. else
  677. {
  678. /* fill in the standard structure */
  679. ss.version = VERSION;
  680. ss.protocol= SS_PROTOCOL_SMTP;
  681. ss.retry_count = 0;
  682. ss.addr_fmt = SS_ADDR_FMT_ASCII_HOST_PORT;
  683. /* open a socket for connecting to the proxy */
  684. sop = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  685. if (sop < 0)
  686. {
  687. log(LOG_DEBUG,"handle_connection() : handle_connection : Error opening socket.");
  688. sendmessage(s,(char *)message,(size_t)512,"451 Could not connect to the onion proxy.%s",SMTPAP_CRLF);
  689. if (dest_addr_str != NULL) {
  690. free(dest_addr_str);
  691. dest_addr_str = NULL;
  692. }
  693. }
  694. else
  695. {
  696. log(LOG_DEBUG,"handle_connection() : handle_connection : Socket opened.");
  697. memset((void *)&op_addr,0,sizeof(op_addr)); /* clear the structure first */
  698. /* set up the sockaddr_in structure */
  699. op_addr.sin_family=AF_INET;
  700. op_addr.sin_port=htons(op_port);
  701. memcpy((void *)&op_addr.sin_addr,local->h_addr,local->h_length);
  702. log(LOG_DEBUG,"handle_connection() : Trying to connect to %s at port %u.",inet_ntoa(*((struct in_addr *)local->h_addr)),op_port);
  703. /* try to connect */
  704. retval = connect(sop,(struct sockaddr *)&op_addr,sizeof(op_addr));
  705. if (retval == -1)
  706. {
  707. sendmessage(s,(char *)message,(size_t)512,"451 Could not connect to the onion proxy.%s",SMTPAP_CRLF);
  708. close(sop);
  709. if (dest_addr_str != NULL)
  710. {
  711. free(dest_addr_str);
  712. dest_addr_str = NULL;
  713. }
  714. }
  715. else /* connection established, now send the standard structure + address and wait for a response */
  716. {
  717. /* write the message to the op_out buffer */
  718. snprintf(dest_port_str,6,"%u",htons(SMTPAP_DEFAULT_SMTP_PORT));
  719. if (op_out != NULL)
  720. {
  721. free(op_out);
  722. op_out = NULL;
  723. }
  724. op_outlen = sizeof(ss) /* standard structure */
  725. + strlen(dest_addr_str) /* destination address */
  726. + 1 /* terminating NULL character */
  727. + strlen(dest_port_str)
  728. + 1; /* terminating NULL character */
  729. op_out = (char *)malloc(op_outlen);
  730. if (!op_out) /* error */
  731. {
  732. log(LOG_DEBUG,"handle_connection() : handle_connection : Could not allocate memory.");
  733. sendmessage(s,(char *)message,(size_t)512,"451 Insufficient memory.%s",SMTPAP_CRLF);
  734. close(sop);
  735. if (dest_addr_str != NULL)
  736. {
  737. free(dest_addr_str);
  738. dest_addr_str = NULL;
  739. }
  740. }
  741. else
  742. {
  743. memcpy(op_out,(void *)&ss,sizeof(ss));
  744. strcpy(op_out+sizeof(ss), dest_addr_str);
  745. strcpy(op_out+sizeof(ss)+strlen(dest_addr_str)+1,dest_port_str);
  746. /* now send the message */
  747. retval = write_tout(sop,op_out,op_outlen,conn_toutp);
  748. /* now clean up the buffers */
  749. op_outlen = 0;
  750. free(op_out);
  751. free(dest_addr_str);
  752. if (retval == -1) /* send failed */
  753. {
  754. log(LOG_DEBUG,"handle_connection() : handle_connection : send() failed.");
  755. sendmessage(s,(char *)message,(size_t)512,"451 Could not send to onion proxy.%s",SMTPAP_CRLF);
  756. close(sop);
  757. }
  758. else /* send seemed to have succeeded */
  759. {
  760. /* wait for the return code */
  761. op_inlen = 1;
  762. op_in = (char *)malloc(op_inlen);
  763. if (!op_in) /* memory allocation failed */
  764. {
  765. log(LOG_DEBUG,"handle_connection() : handle_conection : Could not allocate memory.");
  766. sendmessage(s,(char *)message,(size_t)512,"451 Insufficient memory.%s",SMTPAP_CRLF);
  767. close(sop);
  768. }
  769. else
  770. {
  771. retval = read_tout(sop,op_in,1,0, conn_toutp);
  772. if (retval <= 0) /* recv() failed */
  773. {
  774. log(LOG_DEBUG,"handle_connection() : handle_connection : recv() failed.");
  775. sendmessage(s,(char *)message,(size_t)512,"451 Could not receive data from the onion proxy.%s",SMTPAP_CRLF);
  776. close(sop);
  777. }
  778. else
  779. {
  780. if (!(*op_in)) /* onion proxy says OK */
  781. {
  782. log(LOG_DEBUG,"handle_connection() : handle_connection : received E_SUCCESS from onion proxy");
  783. /* clean up */
  784. free(op_in);
  785. op_inlen=0;
  786. /* allocate both op_in and op_out 512 bytes, the maximum size of an SMTP line */
  787. op_outlen=512;
  788. op_inlen=512;
  789. op_out = (char *)malloc(512);
  790. op_in = (char *)malloc(512);
  791. if ((!op_out) || (!op_in))
  792. {
  793. log(LOG_DEBUG,"handle_connection() : handle_connection : Could not allocate memory.");
  794. sendmessage(s,(char *)message,(size_t)512,"451 Insufficient memory.%s",SMTPAP_CRLF);
  795. close(sop);
  796. }
  797. else
  798. {
  799. /* receive the greeting message from the recipient */
  800. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  801. if (retval == -1) /* could not receive greeting */
  802. {
  803. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving greeting from recipient.");
  804. sendmessage(s,(char *)message,(size_t)512,"451 Error receiving data from the recipient.%s",SMTPAP_CRLF);
  805. }
  806. else /* received greeting */
  807. {
  808. /* send HELO command */
  809. retval = sendmessage(sop,(char *)op_out,(size_t)op_outlen,"HELO ANONYMOUS.smtp.daemon%s",SMTPAP_CRLF);
  810. if (retval == -1)
  811. {
  812. sendmessage(s,(char *)message,(size_t)512,"451 Error sending HELO to the recipient.");
  813. close(sop);
  814. }
  815. else
  816. {
  817. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  818. if (retval == -1)
  819. {
  820. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving HELO response from recipient");
  821. sendmessage(s,(char *)message,(size_t)512,"451 Error receiving data from the recipient.%s",SMTPAP_CRLF);
  822. close(sop);
  823. }
  824. else
  825. {
  826. op_in[retval]=0;
  827. log(LOG_DEBUG,"handle_connection() : handle_connection : Received this from recipient : %s.",op_in);
  828. if (op_in[0] == '2') /* success */
  829. {
  830. /* send MAIL */
  831. if (options[Anonimize].r.i)
  832. retval = sendmessage(sop,(char *)op_out,(size_t)op_outlen,"MAIL From:anonymous@anon.net%s",SMTPAP_CRLF);
  833. else
  834. retval = write_tout(sop,mailbuf,mailbuflen-1,conn_toutp);
  835. if (retval == -1)
  836. {
  837. log(LOG_DEBUG,"handle_connection() : handle_connection : error sending MAIL to recipient");
  838. sendmessage(s,(char *)message,(size_t)512,"451 Error sending MAIL to the recipient.%s",SMTPAP_CRLF);
  839. sendmessage(sop,(char *)op_out,(size_t)op_outlen,"%s%s",SMTPAP_QUIT,SMTPAP_CRLF);
  840. close(sop);
  841. }
  842. else
  843. {
  844. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  845. if (retval == -1)
  846. {
  847. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving MAIL response from recipient");
  848. sendmessage(s,(char *)message,(size_t)512,"451 Error receiving data from the recipient.%s",SMTPAP_CRLF);
  849. close(sop);
  850. }
  851. else
  852. {
  853. op_in[retval]=0;
  854. log(LOG_DEBUG,"handle_connection() : handle_connection : Received this from recipient : %s.",op_in);
  855. if (op_in[0] == '2') /* success */
  856. {
  857. /* send RCPT */
  858. retval = write_tout(sop,rcptbuf,rcptbuflen-1,conn_toutp); /* rcptbuflen includes the terminating NULL character but we don't want to send that */
  859. if (retval == -1)
  860. {
  861. log(LOG_DEBUG,"handle_connection() : handle_connection : error sending RCPT to recipient");
  862. sendmessage(s,(char *)message,(size_t)512,"451 Error sending RCPT to the recipient.%s",SMTPAP_CRLF);
  863. sendmessage(sop,(char *)op_out,(size_t)op_outlen,"%s%s",SMTPAP_QUIT,SMTPAP_CRLF);
  864. close(sop);
  865. }
  866. else
  867. {
  868. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  869. if (retval == -1)
  870. {
  871. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving RCPT response from recipient");
  872. sendmessage(s,(char *)message,(size_t)512,"451 Error receiving data from the recipient.%s",SMTPAP_CRLF);
  873. close(sop);
  874. }
  875. else
  876. {
  877. op_in[retval]=0;
  878. log(LOG_DEBUG,"handle_connection() : handle_connection : Received this from recipient : %s.",op_in);
  879. if (op_in[0] == '2') /* success */
  880. {
  881. sendmessage(s,(char *)message,(size_t)512,"250 Recipient OK.%s",SMTPAP_CRLF);
  882. state = 5;
  883. }
  884. else /* didn't like my RCPT */
  885. {
  886. log(LOG_DEBUG,"handle_connection() : handle_connection : RCPT unsuccessful");
  887. sendmessage(sop,(char *)op_out,(size_t)op_outlen,"%s%s",SMTPAP_QUIT,SMTPAP_CRLF);
  888. close(sop);
  889. sendmessage(s,(char *)message,(size_t)512,"500 Recipient SMTP daemon rejected my RCPT.%s",SMTPAP_CRLF);
  890. }
  891. }
  892. }
  893. }
  894. else /* didn't like my MAIL */
  895. {
  896. log(LOG_DEBUG,"handle_connection() : handle_connection : MAIL unsuccessful");
  897. sendmessage(sop,(char *)op_out,(size_t)op_outlen,"%s%s",SMTPAP_QUIT,SMTPAP_CRLF);
  898. close(sop);
  899. sendmessage(s,(char *)message,(size_t)512,"500 Recipient SMTP daemon rejected my MAIL.%s",SMTPAP_CRLF);
  900. }
  901. }
  902. }
  903. }
  904. else
  905. {
  906. log(LOG_DEBUG,"handle_connection() : handle_connection : HELO unsuccessful");
  907. sendmessage(sop,(char *)op_out,(size_t)op_outlen,"%s%s",SMTPAP_QUIT,SMTPAP_CRLF);
  908. close(sop);
  909. sendmessage(s,(char *)message,(size_t)512,"500 Recipient SMTP daemon rejected my HELO.%s",SMTPAP_CRLF);
  910. }
  911. }
  912. }
  913. }
  914. }
  915. }
  916. else
  917. {
  918. log(LOG_DEBUG,"handle_connection() : handle_connection : onion proxy returned non-zero error code %d.",*op_in);
  919. close(sop);
  920. switch(*op_in)
  921. {
  922. case SS_ERROR_VERSION_UNSUPPORTED :
  923. sendmessage(s,(char *)message,(size_t)512,"500 Onion proxy returned an error (Protocol version not supported).%s",SMTPAP_CRLF);
  924. break;
  925. case SS_ERROR_ADDR_FMT_UNSUPPORTED:
  926. sendmessage(s,(char *)message,(size_t)512,"500 Onion proxy returned an error (Address format not recognised).%s",SMTPAP_CRLF);
  927. break;
  928. case SS_ERROR_INVALID_ADDRESS:
  929. sendmessage(s,(char *)message,(size_t)512,"500 Onion proxy returned an error (Invalid destination address).%s",SMTPAP_CRLF);
  930. break;
  931. case SS_ERROR_INVALID_PORT:
  932. sendmessage(s,(char *)message,(size_t)512,"500 Onion proxy returned an error (Invalid destination port).%s",SMTPAP_CRLF);
  933. break;
  934. default :
  935. sendmessage(s,(char *)message,(size_t)512,"500 Onion proxy returned unexpected error code %d.%s",*op_in,SMTPAP_CRLF);
  936. break;
  937. }
  938. /* clean up */
  939. free(op_in);
  940. op_inlen=0;
  941. }
  942. }
  943. }
  944. }
  945. }
  946. }
  947. }
  948. }
  949. }
  950. }
  951. }
  952. }
  953. }
  954. else
  955. sendmessage(s,(char *)message, (size_t)512,"503 Need RCPT first.%s",SMTPAP_CRLF);
  956. }
  957. else if (state == 5)
  958. {
  959. if ((!strcmp(token,SMTPAP_DATA))) /* received data */
  960. {
  961. partial_dataend = 0;
  962. retval = write_tout(sop, tmpbuf, strlen(tmpbuf), conn_toutp); /* send DATA */
  963. if (retval == -1) /* send(0) failed */
  964. {
  965. log(LOG_DEBUG,"handle_connection() : handle_connection : Failed to send DATA to recipient.");
  966. sendmessage(s,(char *)message,(size_t)512,"451 Error sending DATA to the recipient.%s",SMTPAP_CRLF);
  967. }
  968. else /* get response from the recipient */
  969. {
  970. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  971. if (retval == -1)
  972. {
  973. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving DATA response from recipient");
  974. sendmessage(s,(char *)message,(size_t)512,"451 Error receiving data from the recipient.%s",SMTPAP_CRLF);
  975. }
  976. else
  977. {
  978. op_in[retval]=0;
  979. log(LOG_DEBUG,"handle_connection() : handle_connection : Received this from recipient : %s.",op_in);
  980. if (op_in[0] == '3') /* success */
  981. {
  982. sendmessage(s,(char *)message,(size_t)512,"354 Enter mail, end with \".\" on a line by itself%s",SMTPAP_CRLF);
  983. state = 6;
  984. }
  985. else /* didn't like my DATA */
  986. {
  987. log(LOG_DEBUG,"handle_connection() : handle_connection : DATA unsuccessful");
  988. sendmessage(s,(char *)message,(size_t)512,"500 Recipient SMTP daemon rejected my DATA.%s",SMTPAP_CRLF);
  989. }
  990. }
  991. }
  992. }
  993. else
  994. sendmessage(s,(char *)message, (size_t)512,"503 Expecting DATA.%s",SMTPAP_CRLF);
  995. }
  996. else if (state == 6)
  997. {
  998. /* sanitize the data stream if necessary */
  999. if (options[Anonimize].r.i == 1)
  1000. {
  1001. log(LOG_DEBUG,"handle_connection() : Sanitizing headers ...");
  1002. retval = sanitize_data((unsigned char **)&tmpbuf, &inputlen);
  1003. }
  1004. if ((!retval) || (!options[Anonimize].r.i)) /* sanitization successsful (or wasn't necessary)? */
  1005. {
  1006. log(LOG_DEBUG,"handle_connection() : Attempting to send ...");
  1007. /* forward to recipient */
  1008. retval = write_tout(sop,tmpbuf, inputlen, conn_toutp);
  1009. if (retval == -1)
  1010. {
  1011. log(LOG_DEBUG,"handle_connection() : handle_connection : Failed to forward data to recipient.");
  1012. sendmessage(sop, (char *)op_out, (size_t)op_outlen,"451 Failed to forward data to the recipient.%s",SMTPAP_CRLF);
  1013. }
  1014. else
  1015. {
  1016. /* get the response */
  1017. retval = receive(sop,&op_in,(size_t *)&op_inlen,0);
  1018. if (retval == -1)
  1019. {
  1020. log(LOG_DEBUG,"handle_connection() : handle_connection : error receiving response from recipient");
  1021. sendmessage(s,(char *)message,(size_t)512,"451 Data sent but did not receive a response from the recipient%s.",SMTPAP_CRLF);
  1022. }
  1023. else
  1024. {
  1025. op_in[retval]=0;
  1026. log(LOG_DEBUG,"handle_connection() : handle_connection : Received this from recipient : %s.",op_in);
  1027. if (op_in[0] == '2') /* success */
  1028. {
  1029. sendmessage(s,(char *)message,(size_t)512,"250 Message accepted for delivery.%s",SMTPAP_CRLF);
  1030. sendmessage(sop, (char *)op_out, (size_t)op_outlen,"QUIT%s",SMTPAP_CRLF);
  1031. }
  1032. else /* didn't like my DATA */
  1033. {
  1034. log(LOG_DEBUG,"handle_connection() : handle_connection : DATA unsuccessful");
  1035. sendmessage(s,(char *)message,(size_t)512,"500 Recipient SMTP daemon rejected my DATA.%s",SMTPAP_CRLF);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. else /* sanitization error */
  1041. {
  1042. log(LOG_ERR,"Unable to sanitize an incoming message. Will reject.");
  1043. sendmessage(sop,(char *)op_out, (size_t)op_outlen,"400 Failed to sanitize the data stream.%s", SMTPAP_CRLF);
  1044. }
  1045. /* after state 6 we go back to state 3, regardless of wether the transfer was succesful or not */
  1046. state = 3;
  1047. close(sop);
  1048. free(op_in);op_in=NULL;
  1049. free(op_out);op_out=NULL;
  1050. }
  1051. else /* unexpected state */
  1052. {
  1053. log(LOG_DEBUG,"handle_connection() : handle_connection : Unexpected state!");
  1054. log(LOG_ERR,"An unexpected error has occured. Closing connection.");
  1055. sendmessage(s,(char *)message,(size_t)512,"500 An unexpected error has ocurred. Closing connection.%s",SMTPAP_CRLF);
  1056. break;
  1057. }
  1058. }
  1059. /* clean up */
  1060. if (inbuf != NULL)
  1061. free(inbuf);
  1062. if (tmpbuf != NULL)
  1063. free(tmpbuf);
  1064. if (mailbuf != NULL)
  1065. free(mailbuf);
  1066. if (rcptbuf != NULL)
  1067. free(rcptbuf);
  1068. if (rcptarray != NULL)
  1069. free(rcptarray);
  1070. if (dest_addr_str != NULL)
  1071. free(dest_addr_str);
  1072. if (op_in != NULL)
  1073. free(op_in);
  1074. if (op_out != NULL)
  1075. free(op_out);
  1076. close(sop);
  1077. close(s);
  1078. return retval;
  1079. }
  1080. int main(int argc, char *argv[])
  1081. {
  1082. int retval = 0;
  1083. char c; /* command-line option */
  1084. /* configuration file */
  1085. char *conf_filename = NULL;
  1086. FILE *cf = NULL;
  1087. struct hostent *local_host;
  1088. char local_hostname[512];
  1089. struct sockaddr_in local, remote; /* local and remote address info */
  1090. int request_sock; /* where we listen for connections */
  1091. int new_sock; /* for accepted connections */
  1092. size_t sin_size; /* for accept() calls */
  1093. u_short p; /* smtp proxy port */
  1094. u_short op_port; /* onion proxy port */
  1095. /* used for reaping zombie processes */
  1096. struct sigaction sa;
  1097. char *errtest = NULL; /* for detecting strtoul() errors */
  1098. /* set default listening port */
  1099. p = htons(SMTPAP_LISTEN_PORT);
  1100. /* deal with program arguments */
  1101. if ((argc < 2) && (argc > 5)) /* to few or too many arguments*/
  1102. {
  1103. print_usage();
  1104. return -1;
  1105. }
  1106. opterr = 0;
  1107. while ((c = getopt(argc,argv,args)) != -1)
  1108. {
  1109. switch(c)
  1110. {
  1111. case 'f': /* config file */
  1112. conf_filename = optarg;
  1113. break;
  1114. case 'p':
  1115. p = htons((u_short)strtoul(optarg,&errtest,0));
  1116. if (errtest == optarg) /* error */
  1117. {
  1118. log(LOG_ERR,"Error : -p must be followed by an unsigned positive integer value.");
  1119. print_usage();
  1120. return -1;
  1121. }
  1122. break;
  1123. case 'h':
  1124. print_usage();
  1125. return 0;
  1126. break;
  1127. case 'l':
  1128. if (!strcmp(optarg,"emerg"))
  1129. loglevel = LOG_EMERG;
  1130. else if (!strcmp(optarg,"alert"))
  1131. loglevel = LOG_ALERT;
  1132. else if (!strcmp(optarg,"crit"))
  1133. loglevel = LOG_CRIT;
  1134. else if (!strcmp(optarg,"err"))
  1135. loglevel = LOG_ERR;
  1136. else if (!strcmp(optarg,"warning"))
  1137. loglevel = LOG_WARNING;
  1138. else if (!strcmp(optarg,"notice"))
  1139. loglevel = LOG_NOTICE;
  1140. else if (!strcmp(optarg,"info"))
  1141. loglevel = LOG_INFO;
  1142. else if (!strcmp(optarg,"debug"))
  1143. loglevel = LOG_DEBUG;
  1144. else
  1145. {
  1146. log(LOG_ERR,"Error : argument to -l must be one of alert|crit|err|warning|notice|info|debug.");
  1147. print_usage();
  1148. return -1;
  1149. }
  1150. break;
  1151. case '?':
  1152. if (isprint(c))
  1153. log(LOG_ERR,"Missing argument or unknown option '-%c'.",optopt);
  1154. else
  1155. log(LOG_ERR,"Unknown option character 'x%x'.",optopt);
  1156. print_usage();
  1157. return -1;
  1158. break;
  1159. default:
  1160. abort();
  1161. }
  1162. }
  1163. /* the -f option is mandatory */
  1164. if (conf_filename == NULL)
  1165. {
  1166. log(LOG_ERR,"You must specify a config file with the -f option. See help (-h).");
  1167. return -1;
  1168. }
  1169. /* load config file */
  1170. cf = open_config(conf_filename);
  1171. if (!cf)
  1172. {
  1173. log(LOG_ERR,"Could not open configuration file %s.",conf_filename);
  1174. return -1;
  1175. }
  1176. retval = parse_config(cf,options);
  1177. if (retval)
  1178. return -1;
  1179. if (options[OnionProxy].err != 1)
  1180. {
  1181. log(LOG_ERR,"The OnionProxy option is mandatory.");
  1182. return -1;
  1183. }
  1184. if (options[MaxConn].err != 1)
  1185. {
  1186. log(LOG_ERR,"The MaxConn option is mandatory.");
  1187. return -1;
  1188. }
  1189. if (options[Anonimize].err != 1)
  1190. {
  1191. log(LOG_ERR,"The Anonimize option is mandatory.");
  1192. return -1;
  1193. }
  1194. else if ((options[Anonimize].r.i != 0) && (options[Anonimize].r.i != 1))
  1195. {
  1196. log(LOG_ERR,"The Anonimize option takes the values 1 or 0.");
  1197. return -1;
  1198. }
  1199. if (options[ConnTimeout].err != 1)
  1200. {
  1201. conn_tout.tv_sec = SMTPAP_DEFAULT_CONN_TIMEOUT;
  1202. }
  1203. else
  1204. {
  1205. if (!options[ConnTimeout].r.i)
  1206. conn_toutp = NULL;
  1207. else
  1208. conn_tout.tv_sec = options[ConnTimeout].r.i;
  1209. }
  1210. conn_tout.tv_usec = 0;
  1211. op_port = (u_short)options[OnionProxy].r.i;
  1212. /* get local address so that we know where to get the onion proxy when we need it */
  1213. retval = gethostname(local_hostname, (size_t)512);
  1214. if (retval < 0)
  1215. {
  1216. log(LOG_ERR,"Error getting local hostname");
  1217. return -1;
  1218. }
  1219. local_host = gethostbyname(local_hostname);
  1220. if (!local_host)
  1221. {
  1222. log(LOG_ERR,"Error getting local address.");
  1223. return -1;
  1224. }
  1225. log(LOG_DEBUG,"main() : Got local address : %s.",local_hostname);
  1226. /* get the server up and running */
  1227. request_sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  1228. if (request_sock < 0)
  1229. {
  1230. log(LOG_ERR,"Error opening socket.");
  1231. return -1;
  1232. }
  1233. log(LOG_DEBUG,"Socket opened.");
  1234. memset((void *)&local,0,sizeof(local)); /* clear the structure first */
  1235. /* set up the sockaddr_in structure */
  1236. local.sin_family=AF_INET;
  1237. local.sin_addr.s_addr = INADDR_ANY;
  1238. local.sin_port=p;
  1239. /* bind it to the socket */
  1240. retval = bind(request_sock,(struct sockaddr *)&local, sizeof(local));
  1241. if (retval < 0)
  1242. {
  1243. log(LOG_ERR,"Error binding socket to local port %d.",ntohs(p));
  1244. return retval;
  1245. }
  1246. log(LOG_DEBUG,"Socket bound to port %d.",ntohs(p));
  1247. /* listen for connections */
  1248. retval = listen(request_sock,SOMAXCONN);
  1249. if (retval < 0)
  1250. {
  1251. log(LOG_ERR,"Could not listen for connections.");
  1252. return retval;
  1253. }
  1254. log(LOG_DEBUG,"Listening for connections.");
  1255. /* server should now be up and running */
  1256. /* install the signal handler for making sure zombie processes are killed */
  1257. sa.sa_handler = sigchld_handler;
  1258. sigemptyset(&sa.sa_mask);
  1259. sa.sa_flags = SA_RESTART;
  1260. retval = sigaction(SIGCHLD,&sa,NULL);
  1261. if (retval < 0)
  1262. {
  1263. log(LOG_ERR,"Could not install a signal handler.");
  1264. return -1;
  1265. }
  1266. /* main server loop */
  1267. /* I use a forking server technique - this isn't the most efficient way to do it,
  1268. * but it is simpler. */
  1269. while(1)
  1270. {
  1271. sin_size = sizeof(struct sockaddr_in);
  1272. new_sock = accept(request_sock,(struct sockaddr *)&remote,&sin_size);
  1273. if (new_sock == -1)
  1274. {
  1275. if (errno != EINTR)
  1276. log(LOG_ERR,"Could not accept socket connection.");
  1277. else
  1278. log(LOG_DEBUG,"Interrupt received.");
  1279. continue;
  1280. }
  1281. if (connections >= options[MaxConn].r.i)
  1282. {
  1283. log(LOG_NOTICE,"Number of maximum connections reached. Rejecting incoming request.");
  1284. close(new_sock);
  1285. continue;
  1286. }
  1287. log(LOG_DEBUG,"Accepted a connection from %s.",inet_ntoa(remote.sin_addr));
  1288. connections++;
  1289. if (!fork()) /* this is the child process */
  1290. {
  1291. close(request_sock); /* the child doesn't need the request socket anymore */
  1292. /* Main logic of smtpap. */
  1293. retval = handle_connection(new_sock, local_host, remote, op_port);
  1294. /* End main logic */
  1295. exit(retval); /* done, exit */
  1296. }
  1297. close(new_sock); /* don't need this anymore */
  1298. }
  1299. return retval;
  1300. }