Welcome to mirror list, hosted at ThFree Co, Russian Federation.

smtp.c « smtp « servers « src - github.com/lavabit/magma.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: be2297daf071237da98d12a5697ed0bb12d361de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283

/**
 * @file /magma/servers/smtp/smtp.c
 *
 * @brief	Functions used to handle SMTP commands/actions.
 */

#include "magma.h"

/// TODO: Review error messages and update them with the appropriate response code.

/**
 * @brief	Initialize a TLS session for an unauthenticated SMTP session.
 * @param	con		the connection of the SMTP endpoint requesting the transport layer security upgrade.
 * @return	This function returns no value.
 */
void smtp_starttls(connection_t *con) {

	// Check for an existing TLS connection.
	if (con_secure(con) == 1) {
		con_write_bl(con, "454 Session is already encrypted.\r\n", 35);
		return;
	}
	// Check whether we support the STARTTLS command.
	else if (con_secure(con) == -1) {
		con_write_bl(con, "554 This server has not been configured to support STARTTLS.\r\n", 62);
		return;
	}

	con_write_bl(con, "220 READY\r\n", 11);

	if (!(con->network.tls = tls_server_alloc(con->server, con->network.sockd, M_SSL_BIO_NOCLOSE))) {
		con_write_bl(con, "454 STARTTLS FAILED\r\n", 21);
		log_pedantic("The SSL connection attempt failed.");
		return;
	}

	stats_increment_by_name("smtp.connections.secure");
	st_length_set(con->network.buffer, 0);
	con->network.line = pl_null();
	con->network.status = 1;
	smtp_session_reset(con);

	return;
}

/**
 * @brief	Specify the identity of a message's sender, in response to an SMTP MAIL FROM command.
 * @see		smtp_parse_mail_from_path()
 * @note	This command must be preceded by a HELO command and successful authentication.
 * 			Any prior email address specified by a MAIL FROM command will be overwritten.
 * 			If the SIZE parameter was specified with the MAIL FROM command, its value will be compared to the maximum value specified in
 *	 			the smtp.message_length_limit configuration option.
 * @param	con		the SMTP client connection issuing the command.
 * @return	This function returns no value.
 */
void smtp_mail_from(connection_t *con) {

	// If they try to send this command without saying hello.
	if (!con->smtp.helo && !con->smtp.authenticated) {
		con_write_bl(con, "503 MAIL FROM REJECTED - PLEASE PROVIDE A HELO OR EHLO AND TRY AGAIN\r\n", 70);
		return;
	}

	// If they try to send MAIL FROM twice, trigger a session reset.
	if (con->smtp.mailfrom)	{
		smtp_session_reset(con);
	}

	// Attempt to pull the path off the line.
	if (!(con->smtp.mailfrom = smtp_parse_mail_from_path(con))) {
		con_write_bl(con, "553 MAIL FROM ERROR - INVALID SENDER SYNTAX\r\n", 45);
		return;
	}

	// Make sure the suggested size isn't over the system wide limit.
	if (con->smtp.suggested_length > magma.smtp.message_length_limit) {
		st_free(con->smtp.mailfrom);
		con->smtp.mailfrom = NULL;
		con->smtp.suggested_length = 0;
		con_write_bl(con, "552 MAIL FROM ERROR - SIZE EXCEEDS SYSTEM LIMIT\r\n", 49);
		return;
	}

	// Spit back the all clear.
	con_write_bl(con, "250 MAIL FROM COMPLETE\r\n", 24);

	return;
}

/**
 * @brief	Process an SMTP EHLO command.
 * @see		smtp_parse_helo_domain()
 * @note	Any prior domain specified by a HELO/EHLO command will be overwritten.
 * @param	con		the SMTP client connection issuing the command.
 * @return	This function returns no value.
 */
void smtp_ehlo(connection_t *con) {

	stringer_t *helo;

	if (!(helo = smtp_parse_helo_domain(con))) {
		con_write_bl(con, "501 EHLO SYNTAX ERROR - MISSING REQUIRED DOMAIN PARAMETER\r\n", 59);
		return;
	}

	// Free any previously provided values.
	st_cleanup(con->smtp.helo);
	con->smtp.helo = helo;
	con->smtp.esmtp = true;

	// If the user is connected via SSL already, or there is no SSL context, omit the STARTTLS parameter.
	con_print(con, "250-%.*s\r\n250-8BITMIME\r\n%s250-PIPELINING\r\n250-SIZE %lu\r\n250-AUTH LOGIN PLAIN\r\n250-AUTH=LOGIN PLAIN\r\n250 EHLO COMPLETE\r\n",
		st_length_int(con->server->domain), st_char_get(con->server->domain), (con_secure(con) != 0 ? "" : "250-STARTTLS\r\n"),
		magma.smtp.message_length_limit);

	return;
}

/**
 * @brief	Process an SMTP HELO command.
 * @see		smtp_parse_helo_domain()
 * @note	Any prior domain specified by a HELO/EHLO command will be overwritten.
 * @param	con		the SMTP client connection issuing the command.
 * @return	This function returns no value.
 */
void smtp_helo(connection_t *con) {

	stringer_t *helo;

	if (!(helo = smtp_parse_helo_domain(con))) {
		con_write_bl(con, "501 HELO SYNTAX ERROR - MISSING REQUIRED DOMAIN PARAMETER\r\n", 59);
		return;
	}

	// Free any previously provided values.
	st_cleanup(con->smtp.helo);
	con->smtp.helo = helo;
	con->smtp.esmtp = false;

	// Spit back the standard SMTP greeting..

	con_print(con, "250 %.*s\r\n", st_length_int(con->server->domain), st_char_get(con->server->domain));
	return;
}

/**
 * @brief	Perform an SMTP NOOP (no-operation) command.
 * @note	This command does essentially nothing and is mostly a way to keep connections alive without timing out due to inactivity.
 * @return	This function returns no value.
 */
void smtp_noop(connection_t *con) {

	con_write_bl(con, "250 NOOP COMPLETE\r\n", 19);
	return;
}

/**
 * @brief	A stub function for an SMTP command that has not been implemented.
 * @note	Executing a disabled command while result in a small delay and the protocol violation counter being incremented.
 * @return	This function returns no value.
 */
void smtp_disabled(connection_t *con) {

	con->protocol.violations++;
	usleep(con->server->violations.delay);
	con_print(con, "502 %.*s DISABLED\r\n", (int)con->command->length, con->command->string);

	return;
}

/**
 * @brief	A function that is executed when an invalid SMTP command is executed.
 * @return	This function returns no value.
 */
void smtp_invalid(connection_t *con) {

	con->protocol.violations++;
	usleep(con->server->violations.delay);
	con_write_bl(con, "500 INVALID COMMAND\r\n", 21);

	return;
}

/**
 * @brief	Gracefully terminate an SMTP session, especially in response to an SMTP QUIT command.
 * @note	The standards specify that the receiver MUST send an OK reply, and then close the transmission channel.
 * @param	the SMTP client connection to be terminated.
 * @return	This function returns no value.
 */
void smtp_quit(connection_t *con) {

	if (con_status(con) == 2) {
		con_write_bl(con, "451 Unexpected connection shutdown detected. Goodbye.\r\n", 55);
	}
	else if (con_status(con) > 0) {
		con_write_bl(con, "221 BYE\r\n", 9);
	}
	else if (con_status(con) == 0){
		con_write_bl(con, "421 Network connection failure.\r\n", 33);
	}

	con_flush(con);
	con_destroy(con);

	return;
}

/**
 * @brief	Reset the SMTP session, in response to an SMTP RSET command.
 * @note	This command clears any sender, recipient, and mail data, along with all buffers and state tables.
 * 			The connection structure is reset to the same it was in immediately after the HELO/EHLO command.
 * @param	con		the SMTP client connection issuing the command.
 * @return	This function returns no value.
 */
void smtp_rset(connection_t *con) {

	smtp_session_reset(con);
	con_write_bl(con, "250 RSET COMPLETE\r\n", 19);

	return;
}

void smtp_auth_plain(connection_t *con) {

	int_t state = 0;
	auth_t *auth = NULL;
	smtp_outbound_prefs_t *outbound;
	stringer_t *ip = NULL, *choke = NULL, *subnet = NULL, *invalid = NULL, *decoded = NULL, *argument = NULL;
	placer_t username = { .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA}, password = { .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA},
		authorize_id = { .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA };

	// If the user is already authenticated.
	if (con->smtp.authenticated) {
		con_write_bl(con, "503 ALREADY AUTHENTICATED\r\n", 27);
		return;
	}

	// Store the subnet for tracking login failures. Make the buffer big enough to hold an IPv6 subnet string.
	subnet = con_addr_subnet(con, MANAGEDBUF(256));

	// Generate the authentication choke so only one login attempt is processed per subnet at any given time.
	choke = st_quick(MANAGEDBUF(384), "magma.logins.choke.%.*s", st_length_int(subnet), st_char_get(subnet));

	// Generate the invalid login tracker.
	invalid = st_quick(MANAGEDBUF(384), "magma.logins.invalid.%lu.%.*s", time_datestamp(), st_length_int(subnet), st_char_get(subnet));

	// For now we hard code the maximum number of failed logins.
	if (st_populated(invalid) && cache_increment(invalid, 1, 1, 86400) >= 16) {
		con_write_bl(con, "423 THE MAXIMUM NUMBER OF FAILED LOGIN ATTEMPTS HAS BEEN REACHED - PLEASE TRY AGAIN LATER\r\n", 91);
		con->protocol.violations++;
		return;
	}

	// If AUTH PLAIN is sent without any parameters write the continue code and wait for a line of input data.
	if (!st_cmp_ci_eq(&(con->network.line), PLACER("AUTH PLAIN\r\n", 12)) || !st_cmp_ci_eq(&(con->network.line), PLACER("AUTH PLAIN\n", 11))) {
		if (con_write_bl(con, "334 \r\n", 6) != -1 && con_read_line(con, true) >= 0) {
			argument = smtp_parse_auth(&(con->network.line));
		}
	}

	// Otherwise the authentication data was passed along with the AUTH PLAIN commands, so we simply setup a placer to point_t at it.
	else if (pl_length_get(con->network.line) > 10) {
		argument = smtp_parse_auth(PLACER(pl_char_get(con->network.line) + 10, pl_length_get(con->network.line) - 10));
	}

	// Validate that an argument was extracted using the above logic.
	if (!argument) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		return;
	}

	// Decode the base64 string into its various components.
	decoded = base64_decode(argument, NULL);
	st_free(argument);

	// Make sure we were able to decode something.
	if (!decoded || !st_length_get(decoded)) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		st_cleanup(decoded);
		return;
	}

	// Fetch the different components.
	if (tok_get_st(decoded, '\0', 0, &authorize_id) || tok_get_st(decoded, '\0', 1, &username) || tok_get_st(decoded, '\0', 2, &password) != 1) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		st_free(decoded);
		return;
	}

	// If for some reason the username field is NULL, but the authorize-id isn't, try that instead. We really don't need this.
	if (st_empty(&username) && st_populated(&authorize_id)) {
		mm_copy(&username, &authorize_id, sizeof(placer_t));
	}

	// Error check.
	if (st_empty(&username) || st_empty(&password)) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		st_free(decoded);
		return;
	}

	// Obtain the authentication choke.
	if (lock_get(choke) != 1) {
		con_write_bl(con, "421 THE MAXIMUM NUMBER OF CONCURRENT LOGIN ATTEMPTS HAS BEEN REACHED - PLEASE TRY AGAIN LATER\r\n", 95);
		st_free(decoded);
		return;
	}

	// Process the username, and password, and turn them into authentication tokens.
	state = auth_login(&username, &password, &auth);

	// Release the authentication lock so another connection may proceed.
	lock_release(choke);

	// If the authentication credentials couldn't be processed, return an error.
	if (state) {

		if (state > 0) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - INVALID USERNAME AND PASSWORD COMBINATION\r\n", 72);
		}
		else {
			con_write_bl(con, "423 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		}

		ip = con_addr_presentation(con, MANAGEDBUF(256));
		log_info("Failed login attempt. { ip = %s / username = %.*s / protocol = SMTP }", ip ? st_char_get(ip) : "MISSING",
			st_length_int(&username), st_char_get(&username));

		con->protocol.violations++;
		st_free(decoded);
		return;
	}

	// Check if the account is locked.
	else if (auth->status.locked) {

		if (auth->status.locked == AUTH_LOCK_EXPIRED) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THE SUBSCRIPTION FOR THIS ACCOUNT HAS EXPIRED\r\n", 76);
		}
		else if (auth->status.locked == AUTH_LOCK_ADMIN) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN ADMINISTRATIVELY LOCKED\r\n", 76);
		}
		else if (auth->status.locked == AUTH_LOCK_ABUSE) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED ON SUSPICION OF ABUSE POLICY VIOLATIONS\r\n", 99);
		}
		else if (auth->status.locked == AUTH_LOCK_USER) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED AT THE REQUEST OF THE USER\r\n", 86);
		}
		else {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED\r\n", 59);
		}

		st_free(decoded);
		auth_free(auth);
		return;
	}

	// Authorize the user, and securely delete the keys.
	else if ((state = smtp_fetch_authorization(auth->username, auth->tokens.verification, &outbound))) {

		// In theory the credentials should have been checked above, but just in case we include this error here.
		if (state == -1) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - INVALID USERNAME AND PASSWORD COMBINATION\r\n", 72);
		}
		else if (state == -2) {
			con_write_bl(con, "423 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		}

		st_free(decoded);
		auth_free(auth);
		return;
	}

	// If we have a valid login, we decrement the login counter.
	if (st_populated(invalid)) cache_decrement(invalid, 1, 0, MEMCACHED_EXPIRATION_NOT_ADD);

	// If we made it this far then the connection is authenticated.
	smtp_add_outbound(con, outbound);
	smtp_session_reset(con);
	st_free(decoded);
	auth_free(auth);

	// Adjust the connection object accordingly.
	con->smtp.max_length = outbound->send_size_limit;
	con->smtp.authenticated = true;

	// Let the user know it's all good in cyberspace.
	con_write_bl(con, "235 AUTH PLAIN SUCCESSFUL - AUTHENTICATED\r\n", 43);
	return;
}

void smtp_auth_login(connection_t *con) {

	int_t state = 0;
	auth_t *auth = NULL;
	smtp_outbound_prefs_t *outbound;
	stringer_t *ip = NULL, *choke = NULL, *subnet = NULL, *invalid = NULL, *username = NULL, *password = NULL, *argument = NULL;

	// If the user is already authenticated.
	if (con->smtp.authenticated == true) {
		con_write_bl(con, "503 ALREADY AUTHENTICATED\r\n", 27);
		return;
	}

	// Store the subnet for tracking login failures. Make the buffer big enough to hold an IPv6 subnet string.
	subnet = con_addr_subnet(con, MANAGEDBUF(256));

	// Generate the authentication choke so only one login attempt is processed per subnet at any given time.
	choke = st_quick(MANAGEDBUF(384), "magma.logins.choke.%.*s", st_length_int(subnet), st_char_get(subnet));

	// Generate the invalid login tracker.
	invalid = st_quick(MANAGEDBUF(384), "magma.logins.invalid.%lu.%.*s", time_datestamp(), st_length_int(subnet), st_char_get(subnet));

	// For now we hard code the maximum number of failed logins.
	if (st_populated(invalid) && cache_increment(invalid, 1, 1, 86400) >= 16) {
		con_write_bl(con, "423 THE MAXIMUM NUMBER OF FAILED LOGIN ATTEMPTS HAS BEEN REACHED - PLEASE TRY AGAIN LATER\r\n", 91);
		con->protocol.violations++;
		return;
	}

	// If AUTH LOGIN is sent without any parameters spit out 'Username:' in base64.
	if (!st_cmp_ci_eq(&(con->network.line), PLACER("AUTH LOGIN\r\n", 12)) || !st_cmp_ci_eq(&(con->network.line), PLACER("AUTH LOGIN\n", 11))) {
		if (con_write_bl(con, "334 VXNlcm5hbWU6\r\n", 18) != -1 && con_read_line(con, true) >= 0) {
			argument = smtp_parse_auth(&(con->network.line));
		}
	}

	// Otherwise the authentication data was passed along with the AUTH PLAIN commands, so we simply setup a placer to point at it.
	else if (pl_length_get(con->network.line) > 10) {
		argument = smtp_parse_auth(PLACER(pl_char_get(con->network.line) + 10, pl_length_get(con->network.line) - 10));
	}

	// Validate that an argument was extracted using the above logic.
	if (!argument || !(username = base64_decode(argument, NULL)) || st_empty(username)) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		st_cleanup(argument, username);
		return;
	}

	st_free(argument);
	argument = NULL;

	// Now spit out 'Password:' in base64.
	if (con_write_bl(con, "334 UGFzc3dvcmQ6\r\n", 18) != -1 && con_read_line(con, true) >= 0) {
		argument = smtp_parse_auth(&(con->network.line));
	}

	// Validate that an argument was extracted using the above logic.
	if (!argument || !(password = base64_decode(argument, NULL)) || st_empty(password)) {
		con_write_bl(con, "501 INVALID AUTH SYNTAX\r\n", 25);
		st_cleanup(username, password, argument);
		return;
	}

	st_free(argument);
	argument = NULL;

	// Obtain the authentication choke.
	if (lock_get(choke) != 1) {
		con_write_bl(con, "421 THE MAXIMUM NUMBER OF CONCURRENT LOGIN ATTEMPTS HAS BEEN REACHED - PLEASE TRY AGAIN LATER\r\n", 95);
		st_cleanup(username, password);
		return;
	}

	// Process the username, and password, and turn them into authentication tokens.
	state = auth_login(username, password, &auth);

	// Release the authentication lock so another connection may proceed.
	lock_release(choke);

	// Create the authentication context.
	if (state) {

		if (state < 0) {
			con_write_bl(con, "423 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		}
		else {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - INVALID USERNAME AND PASSWORD COMBINATION\r\n", 72);
		}

		ip = con_addr_presentation(con, MANAGEDBUF(256));
		log_info("Failed login attempt. { ip = %s / username = %.*s / protocol = SMTP }", ip ? st_char_get(ip) : "MISSING",
			st_length_int(username), st_char_get(username));

		st_cleanup(username, password);
		con->protocol.violations++;
		return;
	}

	// Check if the account is locked.
	else if (auth->status.locked) {

		if (auth->status.locked == AUTH_LOCK_EXPIRED) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THE SUBSCRIPTION FOR THIS ACCOUNT HAS EXPIRED\r\n", 76);
		}
		else if (auth->status.locked == AUTH_LOCK_ADMIN) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN ADMINISTRATIVELY LOCKED\r\n", 76);
		}
		else if (auth->status.locked == AUTH_LOCK_ABUSE) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED ON SUSPICION OF ABUSE POLICY VIOLATIONS\r\n", 99);
		}
		else if (auth->status.locked == AUTH_LOCK_USER) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED AT THE REQUEST OF THE USER\r\n", 86);
		}
		else {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - THIS ACCOUNT HAS BEEN LOCKED\r\n", 59);
		}

		st_cleanup(username, password);
		auth_free(auth);
		return;
	}

	// We won't need these again, now that we have the authentication context.
	st_cleanup(username, password);

	// Authorize the user, and securely delete the keys.
	if ((state = smtp_fetch_authorization(auth->username, auth->tokens.verification, &outbound))) {

		// In theory the credentials should have been checked above, but just in case we include this error here.
		if (state == -1) {
			con_write_bl(con, "535 AUTHENTICATION FAILURE - INVALID USERNAME AND PASSWORD COMBINATION\r\n", 72);
		}
		else if (state == -2) {
			con_write_bl(con, "423 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		}

		auth_free(auth);
		return;
	}

	// If we have a valid login, we decrement the login counter.
	if (st_populated(invalid)) cache_decrement(invalid, 1, 0, MEMCACHED_EXPIRATION_NOT_ADD);

	// If we made it this far then the connection is authenticated.
	smtp_add_outbound(con, outbound);
	smtp_session_reset(con);
	auth_free(auth);

	// Adjust the connection object accordingly.
	con->smtp.max_length = outbound->send_size_limit;
	con->smtp.authenticated = true;

	// Let the user know it's all good in cyberspace.
	con_write_bl(con, "235 AUTH PLAIN SUCCESSFUL - AUTHENTICATED\r\n", 43);
	return;
}

void smtp_rcpt_to(connection_t *con) {

	int_t state;
	placer_t domain;
	smtp_inbound_prefs_t *result;
	stringer_t *address = NULL, *sanitized = NULL;

	// If they try to send this command without saying hello.
	if (!(con->smtp.helo) && con->smtp.authenticated == false) {
		con_write_bl(con, "503 RCPT TO REJECTED - PLEASE PROVIDE A HELO OR EHLO AND TRY AGAIN\r\n", 68);
		return;
	}
	else if (!(con->smtp.mailfrom)) {
		con_write_bl(con, "503 RCPT TO REJECTED - PLEASE PROVIDE A MAIL FROM TRY AGAIN\r\n", 61);
		return;
	}

	// Check to make sure we are not over the recipient limit.
	if (con->smtp.num_recipients >= magma.smtp.recipient_limit) {
		con_write_bl(con, "541 RCPT TO REJECTED - PER MESSAGE RECIPIENT LIMIT REACHED\r\n", 50);
		return;
	}

	// Cleanup the input data, if it is blank, reject.
	if (!(address = smtp_parse_rcpt_to(con))) {
		con_write_bl(con, "551 RCPT TO REJECTED - INVALID ADDRESS\r\n", 40);
		return;
	}

	// If the session is authorized, we are going to be relaying this message.
	if (con->smtp.authenticated == true) {

		// Are we only allowing this user to send messages via a secure method?
		if (con->smtp.out_prefs->tls == 1 && con_secure(con) != 1) {
			con_write_bl(con, "530 TRANSPORT LAYER SECURITY REQUIRED - THIS ACCOUNT CAN ONLY BE ACCESSED USING A SECURE NETWORK CONNECTION, PLEASE ENABLE " \
				"SSL OR TLS AND TRY AGAIN\r\n", 149);
			st_free(address);
			return;
		}

		// Make sure the proposed size is good.
		if (con->smtp.suggested_length > con->smtp.out_prefs->send_size_limit) {
			con_print(con, "552 OUTBOUND SIZE LIMIT EXCEEDED - THIS ACCOUNT MAY ONLY SEND MESSAGES UP TO %zu BYTES IN LENGTH\r\n",
				con->smtp.out_prefs->send_size_limit);
			st_free(address);
			return;
		}

		// Has this user exceeded their sending quota.
		if (con->smtp.out_prefs->sent_today + con->smtp.num_recipients >= con->smtp.out_prefs->daily_send_limit) {
			con_print(con, "451 OUTBOUND MAIL QUOTA EXCEEDED - THIS ACCOUNT MAY ONLY SEND %u %s IN A TWENTY-FOUR HOUR PERIOD, PLEASE TRY AGAIN AT A LATER TIME\r\n",
				con->smtp.out_prefs->daily_send_limit, (con->smtp.out_prefs->daily_send_limit != 1) ? "MESSAGES" : "MESSAGE" );
			st_free(address);
			return;
		}

		// Figure out where to store the address.
		if (!smtp_add_recipient(con, address)) {
			con_write_bl(con, "451 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
			st_free(address);
			return;
		}

		con_write_bl(con, "250 RCPT TO ACCEPTED\r\n", 22);
		st_free(address);
		return;
	}

	// Sanitize the email address before attempting a database lookup.
	if (!(sanitized = auth_sanitize_address(address))) {
		con_write_bl(con, "451 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		st_free(address);
		return;
	}

	// Hit the mailboxes table, and see if this is a legitimate address.
	state = smtp_fetch_inbound(sanitized, &result);
	st_free(sanitized);

	// Handle errors, starting with an invalid recipient address.
	if (state == -1) {
		con_print(con, "554 INVALID RECIPIENT - THE EMAIL ADDRESS <%.*s> DOES NOT MATCH AN ACCOUNT ON THIS SYSTEM\r\n",
			st_length_int(address), st_char_get(lower_st(address)));
		st_free(address);
		return;
	}
	// Catch recipient addresses that don't match a locally hosted domain name, and return a slightly more helpful error message.
	else if (state == -2) {
		if (!mail_domain_get(address, &domain)) {
			domain = pl_null();
		}
		con_print(con, "551 RELAY ACCESS DENIED - THE DOMAIN <%.*s> IS NOT HOSTED LOCALLY AND RELAY ACCESS REQUIRES AUTHENTICATION\r\n",
			st_length_int(&domain), st_char_get(lower_st(&domain)));
		st_free(address);
		return;
	}
	// Handle account locks, starting with inactivity locks.
	else if (state == AUTH_LOCK_INACTIVITY) {
		con_print(con, "550 ACCOUNT LOCKED - THE ACCOUNT <%.*s> HAS BEEN LOCKED FOR INACTIVITY\r\n", st_length_int(address),
			st_char_get(lower_st(address)));
		st_free(address);
		return;
	}
	// We skip locks associated with expired account plans. Handle administrative locks.
	if (state == AUTH_LOCK_ADMIN) {
		con_print(con, "550 ACCOUNT LOCKED - THE ACCOUNT <%.*s> HAS BEEN ADMINISTRATIVELY LOCKED\r\n", st_length_int(address),
			st_char_get(lower_st(address)));
		st_free(address);
		return;
	}
	// The account has been locked for abuse.
	else if (state == AUTH_LOCK_ABUSE) {
		con_print(con, "550 ACCOUNT LOCKED - THE ACCOUNT <%.*s> HAS BEEN LOCKED FOR ABUSE POLICY VIOLATIONS\r\n", st_length_int(address),
			st_char_get(lower_st(address)));
		st_free(address);
		return;
	}
	// The user has locked the account.
	else if (state == AUTH_LOCK_USER) {
		con_print(con, "550 ACCOUNT LOCKED - THE ACCOUNT <%.*s> HAS BEEN LOCKED AT THE REQUEST OF THE OWNER\r\n", st_length_int(address),
			st_char_get(lower_st(address)));
		st_free(address);
		return;
	}

	// Catch internal errors, and database problems here. The state value should be -3 if an error occurred, but in the interest
	// of robustness, we simply look for any negative state values we haven't already handled.
	else if ((state != 0 && state != AUTH_LOCK_EXPIRED) || result == NULL) {
		con_write_bl(con, "451 INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\r\n", 52);
		st_free(address);
		return;
	}

	st_free(address);

	// Check for duplicate user numbers.
	if (smtp_check_duplicate_recipient(con, result->usernum)) {
		con->smtp.num_recipients++;
		con_write_bl(con, "250 RCPT TO ACCEPTED\r\n", 22);
		smtp_free_inbound(result);
		return;
	}

	// Make sure the user isn't over their storage quota. If the message is from the admin or contact email address,
	// accept it regardless of whether the account is already over its quota.
	// LOW: This logic seemed to be broken. It was "fixed" but not tested. Make sure quota is only bypassed IF the bypass flag is set.
	if (result->overquota == 1 && !result->rollout && !result->forwarded) {

		if (!(con->smtp.bypass && ((magma.admin.contact && !st_cmp_ci_eq(con->smtp.mailfrom, magma.admin.contact)) ||
			(magma.admin.abuse && !st_cmp_ci_eq(con->smtp.mailfrom, magma.admin.abuse))))) {
			con_print(con, "552 MAILBOX FULL - THE ACCOUNT <%.*s> HAS EXCEEDED THEIR STORAGE QUOTA\r\n", st_length_int(result->rcptto),
				st_char_get(lower_st(result->rcptto)));
			smtp_free_inbound(result);
			return;
		}

	}

	// Check to see if the proposed size is over the established max.
	if (con->smtp.suggested_length > result->recv_size_limit) {
		con_print(con, "552 MESSAGE EXCEEDS SIZE LIMIT - THE ACCOUNT <%.*s> IS ONLY AUTHORIZED TO ACCEPT MESSAGES UP TO %u BYTES\r\n", 	st_length_int(result->rcptto), st_char_get(lower_st(result->rcptto)),
			result->recv_size_limit);
		smtp_free_inbound(result);
		return;
	}

	// Check the connecting server against several RBL databases.
	if (result->rbl == 1) {

		// Perform the check if we haven't performed it yet, or the last attempt resulted in a temporary error.
		if (con->smtp.checked.rbl == 0 || con->smtp.checked.rbl == -1) {
			con->smtp.checked.rbl = smtp_check_rbl(con);
		}

		// If the user has elected to reject these messages.
		if (con->smtp.checked.rbl == -2 && result->rblaction == SMTP_ACTION_REJECT) {

			address = con_addr_presentation(con, MANAGEDBUF(INET6_ADDRSTRLEN));

			con_print(con, "550 MESSAGE BLOCKED - THE ADDRESS [%.*s] HAS BEEN LISTED ON A REALTIME BLACKLIST AND THE ACCOUNT <%.*s> IS CONFIGURED TO " \
				"REJECT MESSAGES FROM BLACKLISTED ADDRESSES\r\n",	st_length_int(address), st_char_get(address),	st_length_int(result->rcptto),
				st_char_get(lower_st(result->rcptto)));

			smtp_free_inbound(result);
			return;
		}

	}

	if (result->greylist == 1) {

		// Check the greylist and see if this IP has tried to e-mail this user before.
		if (smtp_check_greylist(con, result) == 0) {
			con_print(con, "451 MAILBOX UNAVAILABLE - PLEASE TRY AGAIN IN %u %s\r\n", result->greytime, result->greytime != 1 ? "MINUTES" : "MINUTE");
			smtp_free_inbound(result);
			return;
		}

	}

	// Now we check to make sure the user hasn't received too many messages today. Basic mail-bomb defense.
	state = smtp_check_receive_quota(con, result);

	if (state == 1 || state == 2) {

		// Use the first message if the user is over their total, and the second if the IP subnet total is over.
		if (state == 1) {
			con_print(con, "451 MAILBOX UNAVAILABLE - THE ACCOUNT <%.*s> IS CONFIGURED NOT TO ACCEPT MORE THAN %u %s MESSAGES IN A TWENTY-FOUR " \
				"HOUR PERIOD - PLEASE TRY AGAIN LATER\r\n", st_length_int(result->rcptto), st_char_get(lower_st(result->rcptto)), result->daily_recv_limit,
				(result->daily_recv_limit != 1) ? "MESSAGES" : "MESSAGE");
		}
		else {
			con_print(con, "451 MAILBOX UNAVAILABLE - THE ACCOUNT <%.*s> IS CONFIGURED NOT TO ACCEPT MORE THAN %u %s MESSAGES FROM ANY SINGLE SUBNET IN " \
				"A TWENTY-FOUR HOUR PERIOD - PLEASE TRY AGAIN LATER\r\n", st_length_int(result->rcptto), st_char_get(lower_st(result->rcptto)), result->daily_recv_limit_ip,
				(result->daily_recv_limit_ip != 1) ? "MESSAGES" : "MESSAGE");
		}

		smtp_free_inbound(result);
		return;
	}


	// If this user is enforcing SPF.
	if (result->spf == 1) {
		// Perform the SPF check.
		if (!con->smtp.bypass && con->smtp.checked.spf == 0) {
			con->smtp.checked.spf = spf_check(con_addr(con, MEMORYBUF(sizeof(ip_t))), con->smtp.helo, con->smtp.mailfrom);
		}

		/// BUG: Detect messages 'from' a local user/domain and tell them to authenticate first.
		if (con->smtp.checked.spf == -2 && result->spfaction == SMTP_ACTION_REJECT) {

			address = con_addr_presentation(con, MANAGEDBUF(INET6_ADDRSTRLEN));

			con_print(con, "550 MESSAGE BLOCKED - THE MESSAGE IS BEING REJECTED BECAUSE THE ADDRESS [%.*s] IS NOT AUTHORIZED TO SEND "
				"MESSAGES FROM <%.*s> - PLEASE CORRECT THE ISSUE AND TRY AGAIN\r\n", st_length_int(address), st_char_get(address),
				st_length_int(con->smtp.mailfrom), st_char_get(lower_st(con->smtp.mailfrom)));
			smtp_free_inbound(result);
			return;
		}
	}

	// Is this the user with the largest receive size is what?
	if (result->recv_size_limit > con->smtp.max_length) {
		con->smtp.max_length = result->recv_size_limit;
	}

	// Were good, so let the user know.
	smtp_add_inbound(con, result);
	con_write_bl(con, "250 RCPT TO ACCEPTED\r\n", 22);
	return;
}

void smtp_data_finish(connection_t *con, size_t read, int_t checker) {

	chr_t *stream;
	int_t increment;

	// In case we exit early.
	stream = st_data_get(con->network.buffer);

	// If there is no data in the buffer.
	if (read == 0) {
		read = con_read(con);
	}

	while (checker != 4 && status() && read > 0) {

		stream = st_data_get(con->network.buffer);

		for (increment = 0; increment < read && checker != 4; increment++) {
			if (checker == 0 && *stream == '\n') {
				checker++;
			}
			else if (checker == 1 && *stream == '.') {
				checker++;
			}
			else if (checker == 2 && *stream == '\n') {
				checker += 2;
			}
			else if (checker == 2 && *stream == '\r') {
				checker++;
			}
			else if (checker == 3 && *stream == '\n') {
				checker++;
			}
			else if (*stream == '\n') {
				checker = 1;
			}
			else if (checker != 0) {
				checker = 0;
			}
			stream++;
		}

		if (checker != 4) {
			read = con_read(con);
		}
	}

	// So that read line will get anything left in buffer.
	if ((stream - st_char_get(con->network.buffer)) < read) {
		st_data_set(&(con->network.line), st_data_get(con->network.buffer));
		st_length_set(&(con->network.line), stream - st_char_get(con->network.buffer));
	}

	return;
}

int_t smtp_data_read(connection_t *con, stringer_t **message) {

	chr_t *stream, *buffer;
	stringer_t *result, *holder;
	int_t read = 0, increment;
	size_t used = 0, size = 128 * 1024;
	int_t header = 1, checker = 1, carriage = 0;

	// In case we end early.
	*message = NULL;
	stream = st_data_get(con->network.buffer);

	// Expand the stringer in 128 KB chunks.
	if (!(result = st_alloc_opts(MAPPED_T | JOINTED | HEAP, size))) {
		smtp_data_finish(con, 0, checker);
		return -1;
	}

	// Setup the pointer into the stringer.
	buffer = st_char_get(result);
	read = con_read(con);

	while (checker != 4 && read > 0 && status()) {

		// Setup the stream.
		stream = st_data_get(con->network.buffer);

		// Size check.
		if ((read + used) > con->smtp.max_length) {
			log_pedantic("Message exceeded size limit of %zu bytes. Reading till the end, and then returning an error.", con->smtp.max_length);
			smtp_data_finish(con, read, checker);
			st_free(result);
			return -2;
		}

		// Read in the new data.
		for (increment = 0; checker != 4 && increment < read; increment++) {

			// Logic for detecting header mode.
			if (header != 3) {
				if (header == 0 && *stream == '\n') {
					header++;
				}
				else if (header == 1 && *stream == '\n') {
					header += 2;
				}
				else if (header == 1 && *stream == '\r') {
					header++;
				}
				else if (header == 2 && *stream == '\n') {
					header++;
				}
				else if (header != 0) {
					header = 0;
				}
			}

			// Logic for detecting the end of a message.
			if (checker == 0 && *stream == '\n') {
				checker++;
			}
			else if (checker == 1 && *stream == '.') {
				checker++;
			}
			else if (checker == 2 && *stream == '\n') {
				checker += 2;
			}
			else if (checker == 2 && *stream == '\r') {
				checker++;
			}
			else if (checker == 3 && *stream == '\n') {
				checker++;
			}
			else if (*stream == '\n') {
				checker = 1;
			}
			else if (checker != 0) {
				checker = 0;
			}

			// Make sure every line ends with a carriage return, then line break.
			if (*stream == '\n' && carriage == 0) {
				*buffer++ = '\r';
				used++;
			}
			else if (*stream == '\r') {
				carriage = 1;
			}
			else if (carriage != 0) {
				carriage = 0;
			}

			// In header mode, we only read in ASCII (0x00 to 0x7F) characters.
			if (header != 3 && *stream >= 0) {
				*buffer++ = *stream;
				used++;
			}
			// Otherwise we read in anything.
			else if (header == 3) {
				*buffer++ = *stream;
				used++;
			}

			// Make sure we have enough room in the buffer.
			if (used + 32 > size) {
				if ((holder = st_realloc(result, size + (128 * 1024))) == NULL) {
					log_pedantic("Attempted to allocate a buffer of %zu bytes to hold an incoming message, and failed. Returning an error to the client.", size + (128 * 1024));
					smtp_data_finish(con, read, checker);
					st_free(result);
					return -1;
				}

				// Setup the pointers again.
				size += 128 * 1024;
				result = holder;
				buffer = st_char_get(result) + used;
			}

			stream++;
		}

		if (checker != 4) {
			read = con_read(con);
		}
	}

	// The server is shutting down or the client disconnected.
	if (!status()) {
		st_free(result);
		return -3;
	}
	else if (read <= 0) {
		st_free(result);
		return -4;
	}

	// So that read line will get anything left in buffer.
	if ((stream - st_char_get(con->network.buffer)) < read) {
		st_data_set(&(con->network.line), st_data_get(con->network.buffer));
		st_length_set(&(con->network.line), stream - st_char_get(con->network.buffer));
	}

	// Setup the output.
	st_length_set(result, used);
	*message = result;

	return 1;
}

void smtp_data_outbound(connection_t *con) {

	int_t state;
	stringer_t *raw = NULL, *result = NULL, *sanitized = NULL;

	// Check the outbound blocker list.
	if (pattern_check(con->smtp.message->text) == -2) {
		con_write_bl(con, "550 DATA BLOCKED - THIS MESSAGE IS BEING BLOCKED ON SUSPICION OF BEING JUNK MAIL\r\n", 82);
		smtp_session_reset(con);
		return;
	}

	// Check the transmit quota one more time before we actually send the message.
	else if (smtp_check_transmit_quota(con->smtp.out_prefs->usernum, con->smtp.num_recipients, con->smtp.out_prefs) == 1) {
		con_print(con, "451 DATA BLOCKED - THIS USER ACCOUNT IS ONLY ALLOWED TO SEND %u %s IN A TWENTY-FOUR HOUR PERIOD - PLEASE TRY AGAIN LATER\r\n",
			con->smtp.out_prefs->daily_send_limit, (con->smtp.out_prefs->daily_send_limit != 1) ? "MESSAGES" : "MESSAGE");
		smtp_session_reset(con);
		return;
	}
	// We need to extract just the email address from the message header.
	else if (!(raw = mail_extract_address(con->smtp.message->from)) || !(sanitized = auth_sanitize_address(raw))) {
		con_write_bl(con, "550 DATA FAILED - UNABLE TO LOCATE THE \"FROM\" ADDRESS IN THE MESSAGE - PLEASE CHECK YOUR EMAIL CLIENT SETTINGS AND TRY AGAIN\r\n", 126);
		smtp_session_reset(con);
		st_cleanup(raw);
		return;
	}
	// Now check the address in the header.
	else if ((state = smtp_check_authorized_from(con->smtp.out_prefs->usernum, sanitized)) == 0) {
		con_print(con, "550 DATA BLOCKED - THIS USER ACCOUNT IS NOT AUTHORIZED TO SEND MESSAGES WITH THE ADDRESS <%.*s> - PLEASE CHECK YOUR " \
			"EMAIL CLIENT SETTINGS AND TRY AGAIN\r\n", st_length_get(raw), st_char_get(raw));
		smtp_session_reset(con);
		st_free(sanitized);
		st_free(raw);
		return;
	}
	else if (state < 0) {
		con_print(con, "451 DATA FAILED - AN ERROR OCCURRED WHILE CHECKING WHETHER THIS ACCOUNT IS AUTHORIZED TO SEND MESSAGES USING <%.*s> - " \
			"PLEASE TRY AGAIN LATER\r\n", st_length_get(raw), st_char_get(raw));
		smtp_session_reset(con);
		st_free(sanitized);
		st_free(raw);
		return;
	}

	// Check the mail from. If its a designated null sender, use the holder.
	if (!st_cmp_ci_eq(con->smtp.mailfrom, PLACER("<>", 2))) {
		st_free(con->smtp.mailfrom);
		con->smtp.mailfrom = st_dupe(raw);
	}
	else if ((state = smtp_check_authorized_from(con->smtp.out_prefs->usernum, con->smtp.mailfrom)) == 0) {
		con_print(con, "550 DATA BLOCKED - THIS USER ACCOUNT IS NOT AUTHORIZED TO SEND MESSAGES WITH THE ADDRESS <%.*s> - PLEASE CHECK YOUR " \
			"EMAIL CLIENT SETTINGS AND TRY AGAIN\r\n", st_length_get(con->smtp.mailfrom), st_char_get(con->smtp.mailfrom));
		smtp_session_reset(con);
		st_free(sanitized);
		st_free(raw);
		return;
	}
	else if (state < 0) {
		con_print(con, "451 DATA FAILED - AN ERROR OCCURRED WHILE CHECKING WHETHER THIS ACCOUNT IS AUTHORIZED TO SEND MESSAGES USING <%.*s> - " \
			"PLEASE TRY AGAIN LATER\r\n", st_length_get(con->smtp.mailfrom), st_char_get(con->smtp.mailfrom));
		smtp_session_reset(con);
		st_free(sanitized);
		st_free(raw);
		return;
	}

	st_free(sanitized);
	st_free(raw);
	raw = sanitized = NULL;

	// Make sure this message does not contain a virus.
	if ((state = virus_check(con->smtp.message->text)) == -2) {
		con_print(con, "550 DATA BLOCKED - THIS MESSAGE IS BEING BLOCKED BECAUSE IT APPEARS TO CONTAIN A COMPUTER VIRUS OR INTERNET WORM\r\n", 114);
		smtp_session_reset(con);
		return;
	}

	state = smtp_relay_message(con, &result);

	// If the state is non-zero, then status is in the result buffer.
	if (state && result) con_write_st(con, result);

	// Otherwise we print a generic status result
	else con_write_bl(con, "451 DATA FAILED - UNABLE TO RELAY OUTBOUND MESSAGES AT THIS TIME - PLEASE TRY AGAIN LATER\n\n", 91);

	// If the result was positive, we sent the message and need to update the user statistics.
	if (state > 0) smtp_update_transmission_stats(con);

	smtp_session_reset(con);
	st_cleanup(result);
	return;
}

void smtp_data_inbound(connection_t *con) {

	smtp_inbound_prefs_t *current;
	uint32_t perm_errors = 0, temp_errors = 0, delivered = 0, bounces = 0;

	current = con->smtp.in_prefs;
	while (current != NULL) {

		// Process the message.
		current->outcome = smtp_accept_message(con, current);

		// Track the outcomes.
		if (current->outcome == SMTP_OUTCOME_PERM_FAILURE) {
			perm_errors++;
		}
		else if (current->outcome == SMTP_OUTCOME_TEMP_SERVER || current->outcome == SMTP_OUTCOME_TEMP_LOCKED || current->outcome == SMTP_OUTCOME_TEMP_OVERQUOTA) {
			temp_errors++;
		}
		else if (current->outcome != SMTP_OUTCOME_SUCESS) {
			bounces++;
		}
		else {
			delivered++;
		}

		current = (smtp_inbound_prefs_t *) current->next;
	}

	// Tell the connected server what the outcome was.
	if (perm_errors != 0 && !temp_errors && !delivered && !bounces) {
		con_print(con, "551 DATA FAILED - UNABLE TO DELIVER THE MESSAGE TO %s\r\n", con->smtp.num_recipients > 1 ?	"ANY OF THE RECIPIENTS" :	"THE RECIPIENT");
	}
	else if (temp_errors != 0 && !delivered && !bounces) {
		con_print(con, "451 DATA FAILED - ENCOUNTERED A TEMPORARY ERROR WITH %s\r\n", con->smtp.num_recipients > 1 ? "ALL OF THE RECIPIENTS" : "THE RECIPIENT");
	}
	else {
		con_write_bl(con, "250 MESSAGE ACCEPTED\r\n", 22);
		if (temp_errors || perm_errors || bounces) {
			smtp_bounce(con);
		}
	}

	smtp_session_reset(con);

	return;

}

void smtp_data(connection_t *con) {

	int_t state;
	stringer_t *text;
	smtp_message_t *message;

	// Make sure outsiders say HELO.
	// If the remote host tries to send data before sending a MAIL FROM and RCPT TO, return a protocol error.
	if (con->smtp.helo == NULL && con->smtp.authenticated == false) {
		con_write_bl(con, "503 DATA REJECTED - PLEASE PROVIDE A HELO OR EHLO AND TRY AGAIN\r\n", 65);
		smtp_requeue(con);
		return;
	}
	else if (con->smtp.mailfrom == NULL) {
		con_write_bl(con, "503 DATA REJECTED - PLEASE PROVIDE A MAIL FROM AND TRY AGAIN\r\n", 62);
		smtp_requeue(con);
		return;
	}
	else if ((con->smtp.authenticated == false && con->smtp.in_prefs == NULL) || (con->smtp.authenticated == true && con->smtp.out_prefs->recipients == NULL)) {
		con_write_bl(con, "503 DATA REJECTED - PLEASE PROVIDE A RCPT AND TRY AGAIN\r\n", 57);
		smtp_requeue(con);
		return;
	}

	// Tell the user we are ready to receive.
	con_write_bl(con, "354 Enter mail, end with \".\" on a line by itself.\r\n", 51);

	if ((state = smtp_data_read(con, &text)) == -1) {
		con_write_bl(con, "451 DATA FAILED - MEMORY ALLOCATION FAILED - PLEASE TRY AGAIN LATER\r\n", 69);
		smtp_requeue(con);
		return;
	}
	else if (state == -2 && con->smtp.authenticated == true) {
		con_print(con, "552 DATA FAILED - OUTBOUND SIZE LIMIT EXCEEDED - THIS ACCOUNT MAY ONLY SEND MESSAGES UP TO %zu BYTES IN LENGTH\r\n", con->smtp.max_length);
		smtp_requeue(con);
		return;
	}
	else if (state == -2) {
		con_print(con, "552 DATA FAILED - INBOUND SIZE LIMIT EXCEEDED - THE MAILBOXES INDICATED MAY ONLY RECIEVE MESSAGES UP TO %zu BYTES IN LENGTH\r\n", con->smtp.max_length);
		smtp_requeue(con);
		return;
	}
	else if (state == -3) {
		con_write_bl(con, "451 DATA FAILED - THE SERVER IS SHUTTING DOWN FOR MAINTENANCE - PLEASE TRY AGAIN LATER\r\n", 88);
		smtp_quit(con);
		return;
	}
	else if (state == -4) {
		con_write_bl(con, "421 DATA FAILED - THE CONNECTION TIMED OUT WHILE WAITING FOR DATA - GOOD BYE\r\n", 78);
		smtp_quit(con);
		return;
	}
	else if (state < 0) {
		con_write_bl(con, "451 DATA FAILED - INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\n\n", 66);
		smtp_requeue(con);
		return;
	}

	// Count the number of Received lines. Some servers return error code 446 when the number of received lines indicates a delivery
	// loop. Unfortunately that is a temporary error code, which would result in the server attempting delivery again later. Since the
	// problem is unlikely to correct itself, we decided to return a permanent error code instead.
	if (mail_count_received(text) > magma.smtp.relay_limit) {
		con_write_bl(con, "550 DATA FAILED - THE MESSAGE HAS TOO MANY RECEIVED HEADER LINES AND IS BEING REJECTED BECAUSE IT APPEARS TO BE CAUGHT IN A " \
			"FORWARD LOOP\r\n", 138);
		smtp_requeue(con);
		st_free(text);
		return;
	}

	// Setup the message structure and cleanup the message data.
	if (mail_message_cleanup(&text) != 1) {
		con_write_bl(con, "451 DATA FAILED - INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\n\n", 66);
		smtp_requeue(con);
		st_free(text);
		return;
	}

	// Create the message structure.
	if (!(message = mail_create_message(text))) {
		con_write_bl(con, "451 DATA FAILED - INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\n\n", 66);
		smtp_requeue(con);
		st_free(text);
		return;
	}

	// Add all of the required headers.
	if (!mail_add_required_headers(con, message)) {
		con_write_bl(con, "451 DATA FAILED - INTERNAL SERVER ERROR - PLEASE TRY AGAIN LATER\n\n", 66);
		mail_destroy_message(message);
		smtp_requeue(con);
		return;
	}

	// Add the message context to the session.
	con->smtp.message = message;

	if (con->smtp.authenticated == true) {
		requeue(&smtp_data_outbound, &smtp_requeue, con);
	}
	else {
		requeue(&smtp_data_inbound, &smtp_requeue, con);
	}

	return;
}

/**
 * @brief	The start of the protocol handler for the SMTP server.
 * @param	con		the new inbound SMTP client connection.
 * @return	This function returns no value.
 */
void smtp_init(connection_t *con) {

	// Does this connection come from a trusted IP?
	if (smtp_bypass_check(con)) {
		con->smtp.bypass = 1;
	}

	// Queue a reverse lookup.
	con_reverse_enqueue(con);

	// Print_t the greeting and queue for a new command.
	con_print(con, "220 %.*s ESMTP Magma\r\n", st_length_int(con->server->domain), st_char_get(con->server->domain));
	smtp_requeue(con);

	return;
}

void submission_init(connection_t *con) {

	con->smtp.submission = true;
	smtp_init(con);

	return;
}