-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSISMTPMessage.m
848 lines (716 loc) · 35.1 KB
/
SISMTPMessage.m
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
//
// SISMTPMessage.m
// SIKit
//
// Created by Matias Pequeno on 10/5/10.
// Copyright 2010 Silicon Illusions, Inc. All rights reserved.
//
#import "SISMTPMessage.h"
#import "SIFoundationExtension.h"
#import "SIUtil.h"
NSString *kSISMTPPartContentDispositionKey = @"kSISMTPPartContentDispositionKey";
NSString *kSISMTPPartContentTypeKey = @"kSISMTPPartContentTypeKey";
NSString *kSISMTPPartMessageKey = @"kSISMTPPartMessageKey";
NSString *kSISMTPPartContentTransferEncodingKey = @"kSISMTPPartContentTransferEncodingKey";
#define SHORT_LIVENESS_TIMEOUT 20.0
#define LONG_LIVENESS_TIMEOUT 60.0
@interface SISMTPMessage ()
@property (nonatomic, readwrite, strong) NSMutableString *inputString;
@property (nonatomic, readwrite, strong) NSTimer *connectTimer;
@property (nonatomic, readwrite, strong) NSTimer *watchdogTimer;
- (void)parseBuffer;
- (BOOL)sendParts;
- (void)cleanUpStreams;
- (void)startShortWatchdog;
- (void)stopWatchdog;
- (NSString *)formatAnAddress:(NSString *)address;
- (NSString *)formatAddresses:(NSString *)addresses;
@end
@implementation SISMTPMessage
{
NSOutputStream *outputStream;
NSInputStream *inputStream;
SISMTPState sendState;
BOOL isSecure;
// Auth support flags
BOOL serverAuthCRAMMD5;
BOOL serverAuthPLAIN;
BOOL serverAuthLOGIN;
BOOL serverAuthDIGESTMD5;
// Content support flags
BOOL server8bitMessages;
}
- (id)init
{
static NSArray *defaultPorts = nil;
if (!defaultPorts)
{
defaultPorts = @[@(25), @(465), @(587)];
}
if (self = [super init])
{
// Setup the default ports
self.relayPorts = defaultPorts;
// setup a default timeout (8 seconds)
_connectTimeout = 8.0;
// by default, validate the SSL chain
_validateSSLChain = YES;
}
return self;
}
- (void)dealloc
{
inputStream = nil;
outputStream = nil;
[self.connectTimer invalidate];
[self stopWatchdog];
}
- (id)copyWithZone:(NSZone *)zone
{
SISMTPMessage *smtpMessageCopy = [[[self class] allocWithZone:zone] init];
smtpMessageCopy.delegate = self.delegate;
smtpMessageCopy.fromEmail = self.fromEmail;
smtpMessageCopy.login = self.login;
smtpMessageCopy.parts = [self.parts copy];
smtpMessageCopy.pass = self.pass;
smtpMessageCopy.relayHost = self.relayHost;
smtpMessageCopy.requiresAuth = self.requiresAuth;
smtpMessageCopy.subject = self.subject;
smtpMessageCopy.toEmail = self.toEmail;
smtpMessageCopy.wantsSecure = self.wantsSecure;
smtpMessageCopy.validateSSLChain = self.validateSSLChain;
smtpMessageCopy.ccEmail = self.ccEmail;
smtpMessageCopy.bccEmail = self.bccEmail;
return smtpMessageCopy;
}
- (void)startShortWatchdog
{
LogInfo(@"*** starting short watchdog ***");
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SHORT_LIVENESS_TIMEOUT target:self selector:@selector(connectionWatchdog:) userInfo:nil repeats:NO];
}
- (void)startLongWatchdog
{
LogInfo(@"*** starting long watchdog ***");
self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:LONG_LIVENESS_TIMEOUT target:self selector:@selector(connectionWatchdog:) userInfo:nil repeats:NO];
}
- (void)stopWatchdog
{
LogInfo(@"*** stopping watchdog ***");
[self.watchdogTimer invalidate];
self.watchdogTimer = nil;
}
- (BOOL)send
{
NSAssert(sendState == kSISMTPIdle, @"Message has already been sent!");
if (_requiresAuth)
{
NSAssert(_login, @"auth requires login");
NSAssert(_pass, @"auth requires pass");
}
NSAssert(_relayHost, @"send requires relayHost");
NSAssert(_subject, @"send requires subject");
NSAssert(_fromEmail, @"send requires fromEmail");
NSAssert(_toEmail, @"send requires toEmail");
NSAssert(_parts, @"send requires parts");
if (![_relayPorts count])
{
[_delegate messageFailed:self
error:[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Unable to connect to the server.", @"server connection fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try sending your message again later.", @"server generic error recovery")}]];
return NO;
}
// Grab the next relay port
short relayPort = [_relayPorts[0] shortValue];
// Pop this off the head of the queue.
self.relayPorts = ([_relayPorts count] > 1) ? [_relayPorts subarrayWithRange:NSMakeRange(1, [_relayPorts count] - 1)] : @[];
LogInfo(@"C: Attempting to connect to server at: %@:%d", _relayHost, relayPort);
self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:_connectTimeout
target:self
selector:@selector(connectionConnectedCheck:)
userInfo:nil
repeats:NO];
NSInputStream * is = nil;
NSOutputStream * os = nil;
[NSStream getStreamsToHostNamed:_relayHost port:relayPort inputStream:&is outputStream:&os];
inputStream = is;
outputStream = os;
if ((inputStream != nil) && (outputStream != nil))
{
sendState = kSISMTPConnecting;
isSecure = NO;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[inputStream open];
[outputStream open];
self.inputString = [NSMutableString string];
return YES;
}
else
{
[self.connectTimer invalidate];
self.connectTimer = nil;
[_delegate messageFailed:self
error:[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorConnectionFailed
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Unable to connect to the server.", @"server connection fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try sending your message again later.", @"server generic error recovery")}]];
return NO;
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode)
{
case NSStreamEventHasBytesAvailable:
{
uint8_t buf[1024];
memset(buf, 0, sizeof(uint8_t) * 1024);
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len)
{
NSString *tmpStr = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding];
[_inputString appendString:tmpStr];
[self parseBuffer];
}
break;
}
case NSStreamEventEndEncountered:
{
[self stopWatchdog];
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
if (sendState != kSISMTPMessageSent)
{
[_delegate messageFailed:self
error:[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorConnectionInterrupted
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"The connection to the server was interrupted.", @"server connection interrupted error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try sending your message again later.", @"server generic error recovery")}]];
}
break;
}
default:
break;
}
}
- (NSString *)formatAnAddress:(NSString *)address
{
NSString *formattedAddress;
NSCharacterSet *whitespaceCharSet = [NSCharacterSet whitespaceCharacterSet];
if (([address rangeOfString:@"<"].location == NSNotFound) && ([address rangeOfString:@">"].location == NSNotFound)) {
formattedAddress = [NSString stringWithFormat:@"RCPT TO:<%@>\r\n", [address stringByTrimmingCharactersInSet:whitespaceCharSet]];
}
else {
formattedAddress = [NSString stringWithFormat:@"RCPT TO:%@\r\n", [address stringByTrimmingCharactersInSet:whitespaceCharSet]];
}
return(formattedAddress);
}
- (NSString *)formatAddresses:(NSString *)addresses
{
NSCharacterSet *splitSet = [NSCharacterSet characterSetWithCharactersInString:@";,"];
NSMutableString *multipleRcptTo = [NSMutableString string];
if ((addresses != nil) && (![addresses isEqualToString:@""])) {
if( [addresses rangeOfString:@";"].location != NSNotFound || [addresses rangeOfString:@","].location != NSNotFound ) {
NSArray *addressParts = [addresses componentsSeparatedByCharactersInSet:splitSet];
for( NSString *address in addressParts ) {
[multipleRcptTo appendString:[self formatAnAddress:address]];
}
}
else {
[multipleRcptTo appendString:[self formatAnAddress:addresses]];
}
}
return(multipleRcptTo);
}
- (void)parseBuffer
{
// Pull out the next line
NSScanner *scanner = [NSScanner scannerWithString:_inputString];
NSString *tmpLine = nil;
NSError *error = nil;
BOOL encounteredError = NO;
BOOL messageSent = NO;
while (![scanner isAtEnd])
{
BOOL foundLine = [scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet]
intoString:&tmpLine];
if (foundLine)
{
[self stopWatchdog];
LogInfo(@"S: %@", tmpLine);
switch (sendState)
{
case kSISMTPConnecting:
{
if ([tmpLine hasPrefix:@"220 "])
{
sendState = kSISMTPWaitingEHLOReply;
NSString *ehlo = [NSString stringWithFormat:@"EHLO %@\r\n", @"localhost"];
LogInfo(@"C: %@", ehlo);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[ehlo UTF8String], [ehlo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
break;
}
case kSISMTPWaitingEHLOReply:
{
// Test auth login options
if ([tmpLine hasPrefix:@"250-AUTH"])
{
NSRange testRange;
testRange = [tmpLine rangeOfString:@"CRAM-MD5"];
if (testRange.location != NSNotFound)
{
serverAuthCRAMMD5 = YES;
}
testRange = [tmpLine rangeOfString:@"PLAIN"];
if (testRange.location != NSNotFound)
{
serverAuthPLAIN = YES;
}
testRange = [tmpLine rangeOfString:@"LOGIN"];
if (testRange.location != NSNotFound)
{
serverAuthLOGIN = YES;
}
testRange = [tmpLine rangeOfString:@"DIGEST-MD5"];
if (testRange.location != NSNotFound)
{
serverAuthDIGESTMD5 = YES;
}
}
else if ([tmpLine hasPrefix:@"250-8BITMIME"])
{
server8bitMessages = YES;
}
else if ([tmpLine hasPrefix:@"250-STARTTLS"] && !isSecure && _wantsSecure)
{
// if we're not already using TLS, start it up
sendState = kSISMTPWaitingTLSReply;
NSString *startTLS = @"STARTTLS\r\n";
LogInfo(@"C: %@", startTLS);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[startTLS UTF8String], [startTLS lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else if ([tmpLine hasPrefix:@"250 "])
{
if (self.requiresAuth)
{
// Start up auth
if (serverAuthPLAIN)
{
sendState = kSISMTPWaitingAuthSuccess;
NSString *loginString = [NSString stringWithFormat:@"\000%@\000%@", _login, _pass];
NSString *authString = [NSString stringWithFormat:@"AUTH PLAIN %@\r\n", [[loginString dataUsingEncoding:NSUTF8StringEncoding] encodeBase64ForData]];
LogInfo(@"C: %@", authString);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[authString UTF8String], [authString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else if (serverAuthLOGIN)
{
sendState = kSISMTPWaitingLOGINUsernameReply;
NSString *authString = @"AUTH LOGIN\r\n";
LogInfo(@"C: %@", authString);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[authString UTF8String], [authString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else
{
error = [NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorUnsupportedLogin
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Unsupported login mechanism.", @"server unsupported login fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Your server's security setup is not supported, please contact your system administrator or use a supported email account like MobileMe.", @"server security fail error recovery")}];
encounteredError = YES;
}
}
else
{
// Start up send from
sendState = kSISMTPWaitingFromReply;
NSString *mailFrom = [NSString stringWithFormat:@"MAIL FROM:<%@>\r\n", _fromEmail];
LogInfo(@"C: %@", mailFrom);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[mailFrom UTF8String], [mailFrom lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
}
break;
}
case kSISMTPWaitingTLSReply:
{
if ([tmpLine hasPrefix:@"220 "])
{
// Attempt to use TLSv1
CFMutableDictionaryRef sslOptions = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelTLSv1);
if (!self.validateSSLChain)
{
// Don't validate SSL certs. This is terrible, please complain loudly to your BOFH.
LogWarning(@"Will not validate SSL chain!!!");
CFDictionarySetValue(sslOptions, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);
CFDictionarySetValue(sslOptions, kCFStreamSSLAllowsExpiredCertificates, kCFBooleanTrue);
CFDictionarySetValue(sslOptions, kCFStreamSSLAllowsExpiredRoots, kCFBooleanTrue);
CFDictionarySetValue(sslOptions, kCFStreamSSLAllowsAnyRoot, kCFBooleanTrue);
}
LogInfo(@"Beginning TLSv1...");
CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, sslOptions);
CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, sslOptions);
CFRelease(sslOptions);
// restart the connection
sendState = kSISMTPWaitingEHLOReply;
isSecure = YES;
NSString *ehlo = [NSString stringWithFormat:@"EHLO %@\r\n", @"localhost"];
LogInfo(@"C: %@", ehlo);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[ehlo UTF8String], [ehlo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
/*
else
{
error = [NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorTLSFail
userInfo:[NSDictionary dictionaryWithObject:@"Unable to start TLS"
forKey:NSLocalizedDescriptionKey]];
encounteredError = YES;
}
*/
}
}
case kSISMTPWaitingLOGINUsernameReply:
{
if ([tmpLine hasPrefix:@"334 VXNlcm5hbWU6"])
{
sendState = kSISMTPWaitingLOGINPasswordReply;
NSString *authString = [NSString stringWithFormat:@"%@\r\n", [[_login dataUsingEncoding:NSUTF8StringEncoding] encodeBase64ForData]];
LogInfo(@"C: %@", authString);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[authString UTF8String], [authString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
break;
}
case kSISMTPWaitingLOGINPasswordReply:
{
if ([tmpLine hasPrefix:@"334 UGFzc3dvcmQ6"])
{
sendState = kSISMTPWaitingAuthSuccess;
NSString *authString = [NSString stringWithFormat:@"%@\r\n", [[_pass dataUsingEncoding:NSUTF8StringEncoding] encodeBase64ForData]];
LogInfo(@"C: %@", authString);
if( SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[authString UTF8String], [authString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0 )
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
break;
}
case kSISMTPWaitingAuthSuccess:
{
if ([tmpLine hasPrefix:@"235 "])
{
sendState = kSISMTPWaitingFromReply;
NSString *mailFrom = server8bitMessages ? [NSString stringWithFormat:@"MAIL FROM:<%@> BODY=8BITMIME\r\n", _fromEmail] : [NSString stringWithFormat:@"MAIL FROM:<%@>\r\n", _fromEmail];
LogInfo(@"C: %@", mailFrom);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[mailFrom cStringUsingEncoding:NSASCIIStringEncoding], [mailFrom lengthOfBytesUsingEncoding:NSASCIIStringEncoding]) < 0)
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else if ([tmpLine hasPrefix:@"535 "])
{
error =[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorInvalidUserPass
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid username or password.", @"server login fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Go to Email Preferences in the application and re-enter your username and password.", @"server login error recovery")}];
encounteredError = YES;
}
break;
}
case kSISMTPWaitingFromReply:
{
// toc 2009-02-18 begin changes per mdesaro issue 18 - http://code.google.com/p/skpsmtpmessage/issues/detail?id=18
// toc 2009-02-18 begin changes to support cc & bcc
if ([tmpLine hasPrefix:@"250 "]) {
sendState = kSISMTPWaitingToReply;
NSMutableString *multipleRcptTo = [NSMutableString string];
[multipleRcptTo appendString:[self formatAddresses:_toEmail]];
[multipleRcptTo appendString:[self formatAddresses:_ccEmail]];
[multipleRcptTo appendString:[self formatAddresses:_bccEmail]];
LogInfo(@"C: %@", multipleRcptTo);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[multipleRcptTo UTF8String], [multipleRcptTo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0)
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
break;
}
case kSISMTPWaitingToReply:
{
if ([tmpLine hasPrefix:@"250 "])
{
sendState = kSISMTPWaitingForEnterMail;
NSString *dataString = @"DATA\r\n";
LogInfo(@"C: %@", dataString);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[dataString UTF8String], [dataString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0)
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else if ([tmpLine hasPrefix:@"530 "])
{
error =[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorNoRelay
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Relay rejected.", @"server relay fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Your server probably requires a username and password.", @"server relay fail error recovery")}];
encounteredError = YES;
}
else if ([tmpLine hasPrefix:@"550 "])
{
error =[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorInvalidMessage
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"To address rejected.", @"server to address fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Please re-enter the To: address.", @"server to address fail error recovery")}];
encounteredError = YES;
}
break;
}
case kSISMTPWaitingForEnterMail:
{
if ([tmpLine hasPrefix:@"354 "])
{
sendState = kSISMTPWaitingSendSuccess;
if (![self sendParts])
{
error = [outputStream streamError];
encounteredError = YES;
}
}
break;
}
case kSISMTPWaitingSendSuccess:
{
if ([tmpLine hasPrefix:@"250 "])
{
sendState = kSISMTPWaitingQuitReply;
NSString *quitString = @"QUIT\r\n";
LogInfo(@"C: %@", quitString);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[quitString UTF8String], [quitString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0)
{
error = [outputStream streamError];
encounteredError = YES;
}
else
{
[self startShortWatchdog];
}
}
else if ([tmpLine hasPrefix:@"550 "])
{
error =[NSError errorWithDomain:@"SISMTPMessageError"
code:kSISMTPErrorInvalidMessage
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Failed to logout.", @"server logout fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try sending your message again later.", @"server generic error recovery")}];
encounteredError = YES;
}
}
case kSISMTPWaitingQuitReply:
{
if ([tmpLine hasPrefix:@"221 "])
{
sendState = kSISMTPMessageSent;
messageSent = YES;
}
}
}
}
else
{
break;
}
}
self.inputString = [[_inputString substringFromIndex:[scanner scanLocation]] mutableCopy];
if (messageSent)
{
[self cleanUpStreams];
[_delegate messageSent:self];
}
else if (encounteredError)
{
[self cleanUpStreams];
[_delegate messageFailed:self error:error];
}
}
- (BOOL)sendParts
{
NSMutableString *message = [[NSMutableString alloc] init];
static NSString *separatorString = @"--SISMTPMessage--Separator--Delimiter\r\n";
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuid = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidRef));
CFRelease(uuidRef);
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
[message appendFormat:@"Date: %@\r\n", [dateFormatter stringFromDate:now]];
[message appendFormat:@"Message-id: <%@@%@>\r\n", [(NSString *)uuid stringByReplacingOccurrencesOfString:@"-" withString:@""], self.relayHost];
[message appendFormat:@"From:%@\r\n", _fromEmail];
if ((self.toEmail != nil) && (![self.toEmail isEqualToString:@""]))
{
[message appendFormat:@"To:%@\r\n", self.toEmail];
}
if ((self.ccEmail != nil) && (![self.ccEmail isEqualToString:@""]))
{
[message appendFormat:@"Cc:%@\r\n", self.ccEmail];
}
[message appendString:@"Content-Type: multipart/mixed; boundary=SISMTPMessage--Separator--Delimiter\r\n"];
[message appendString:@"Mime-Version: 1.0 (SISMTPMessage 1.0)\r\n"];
[message appendFormat:@"Subject:%@\r\n\r\n",_subject];
[message appendString:separatorString];
NSData *messageData = [message dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
LogInfo(@"C: %s", [messageData bytes], [messageData length]);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[messageData bytes], [messageData length]) < 0)
{
return NO;
}
message = [[NSMutableString alloc] init];
for (NSDictionary *part in _parts)
{
if (part[kSISMTPPartContentDispositionKey])
{
[message appendFormat:@"Content-Disposition: %@\r\n", part[kSISMTPPartContentDispositionKey]];
}
[message appendFormat:@"Content-Type: %@\r\n", part[kSISMTPPartContentTypeKey]];
[message appendFormat:@"Content-Transfer-Encoding: %@\r\n\r\n", part[kSISMTPPartContentTransferEncodingKey]];
[message appendString:part[kSISMTPPartMessageKey]];
[message appendString:@"\r\n"];
[message appendString:separatorString];
}
[message appendString:@"\r\n.\r\n"];
LogInfo(@"C: %@", message);
if (SIWriteStreamWriteFully((__bridge CFWriteStreamRef)outputStream, (const uint8_t *)[message UTF8String], [message lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) < 0)
{
return NO;
}
[self startLongWatchdog];
return YES;
}
- (void)connectionConnectedCheck:(NSTimer *)aTimer
{
if (sendState == kSISMTPConnecting)
{
[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
inputStream = nil;
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
outputStream = nil;
// Try the next port - if we don't have another one to try, this will fail
sendState = kSISMTPIdle;
[self send];
}
self.connectTimer = nil;
}
- (void)connectionWatchdog:(NSTimer *)aTimer
{
[self cleanUpStreams];
// No hard error if we're wating on a reply
if (sendState != kSISMTPWaitingQuitReply)
{
NSError *error = [NSError errorWithDomain:@"SISMTPMessageError"
code:kSKPSMPTErrorConnectionTimeout
userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Timeout sending message.", @"server timeout fail error description"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try sending your message again later.", @"server generic error recovery")}];
[_delegate messageFailed:self error:error];
}
else
{
[_delegate messageSent:self];
}
}
- (void)cleanUpStreams
{
[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
inputStream = nil;
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
outputStream = nil;
}
@end