File: CWPOP3Store.m

package info (click to toggle)
pantomime 1.4.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,288 kB
  • sloc: objc: 22,039; makefile: 11; sh: 4
file content (1030 lines) | stat: -rw-r--r-- 22,978 bytes parent folder | download
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
/*
**  CWPOP3Store.m
**
**  Copyright (c) 2001-2006 Ludovic Marcotte
**  Copyright (C) 2017-2022 Riccardo Mottola
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**          Riccardo Mottola <rm@gnu.org>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**  Lesser General Public License for more details.
**  
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Pantomime/CWPOP3Store.h>

#import <Pantomime/CWConstants.h>
#import <Pantomime/CWMD5.h>
#import <Pantomime/CWMIMEUtility.h>
#import <Pantomime/NSData+Extensions.h>
#import <Pantomime/CWPOP3CacheManager.h>
#import <Pantomime/CWPOP3Folder.h>
#import <Pantomime/CWPOP3Message.h>
#import <Pantomime/CWStore.h>
#import <Pantomime/CWTCPConnection.h>
#import <Pantomime/CWURLName.h>

#import <Foundation/NSArray.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSException.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSPathUtilities.h>

#include <stdio.h>

//
// Some static variables used to enhance the performance.
//
static NSStringEncoding defaultCStringEncoding;
static NSData *CRLF;

//
//
//
@interface CWPOP3QueueObject : NSObject
{
  @public
    POP3Command command;
    NSString *arguments;
}
- (id) initWithCommand: (POP3Command) theCommand
	     arguments: (NSString *) theArguments;
@end

@implementation CWPOP3QueueObject

- (id) initWithCommand: (POP3Command) theCommand
	     arguments: (NSString *) theArguments
{
  self = [super init];
  if (self)
    {
      command = theCommand;
      ASSIGN(arguments, theArguments);
    }
  return self;
}

- (void) dealloc
{
  RELEASE(arguments);
  [super dealloc];
}
@end



//
// Private methods
//
@interface CWPOP3Store (Private)

- (void) _parseAPOP;
- (void) _parseAUTHORIZATION;
- (void) _parseCAPA;
- (void) _parseLIST;
- (void) _parseNOOP;
- (void) _parsePASS;
- (void) _parseQUIT;
- (void) _parseRETR;
- (void) _parseSTAT;
- (void) _parseSTLS;
- (void) _parseTOP;
- (void) _parseUIDL;
- (void) _parseUSER;
- (void) _parseServerOutput;

@end


//
//
//
@implementation CWPOP3Store

+ (void) initialize
{
  defaultCStringEncoding = [NSString defaultCStringEncoding];
  CRLF = [[NSData alloc] initWithBytes: "\r\n"  length: 2];
}


//
//
//
- (id) initWithName: (NSString *) theName
	       port: (unsigned int) thePort
{
  if (thePort == 0) thePort = 110;

  self = [super initWithName: theName  port: thePort];
  if (self)
    {
      _lastCommand = POP3_AUTHORIZATION;
      _timestamp = nil;
  
      // We initialize out POP3Folder object.
      _folder = [[CWPOP3Folder alloc] initWithName: @"Inbox"];
      [_folder setStore: self];
  
      // We queue our first "command".
      [_queue addObject: AUTORELEASE([[CWPOP3QueueObject alloc] initWithCommand: _lastCommand  arguments: @""])];
    }
  
  return self;
}


//
//
//
- (void) dealloc
{
  //NSLog(@"POP3Store: -dealloc");
  RELEASE(_folder);
  RELEASE(_timestamp);

  [super dealloc];
}


//
//
//
- (id) initWithURL: (CWURLName *) theURL
{
  return [self initWithName: [theURL host]  port: 110];
}


//
//
//
- (NSEnumerator *) folderEnumerator
{
  return [[NSArray arrayWithObject: @"Inbox"] objectEnumerator];
}


//
//
//
- (NSEnumerator *) subscribedFolderEnumerator
{
  return [self folderEnumerator];
}


//
//
//
- (NSEnumerator *) openFoldersEnumerator
{
  return [[NSArray arrayWithObject: _folder] objectEnumerator];
}


//
//
//
- (void) removeFolderFromOpenFolders: (CWFolder *) theFolder
{
  // Do nothing
}


//
// This method authenticates the Store to the POP3 server.
// In case of an error, it returns NO.
//
- (void) authenticate: (NSString *) theUsername
	     password: (NSString *) thePassword
	    mechanism: (NSString *) theMechanism
{
  ASSIGN(_username, theUsername);
  ASSIGN(_password, thePassword);
  ASSIGN(_mechanism, theMechanism);
  
  // We verify if we must use APOP
  if (theMechanism && [theMechanism caseInsensitiveCompare: @"APOP"] == NSOrderedSame)
    {
      NSMutableData *aMutableData;
      CWMD5 *aMD5;
      
      aMutableData = [[NSMutableData alloc] init];
      [aMutableData appendCFormat:  @"%@%@", _timestamp, _password];
      aMD5 = [[CWMD5 alloc] initWithData: aMutableData];
      RELEASE(aMutableData);

      [aMD5 computeDigest];

      [self sendCommand: POP3_APOP  arguments: @"APOP %@ %@", _username, [aMD5 digestAsString]];
      RELEASE(aMD5);
    }
  else
    {
      [self sendCommand: POP3_USER  arguments: @"USER %@", _username];
    }
}


//
//
//
- (NSArray *) supportedMechanisms
{
  if (_timestamp)
    {
      return [NSArray arrayWithObject: @"APOP"];
    }
  
  return [NSArray array];
}


//
// The default folder in POP3 is always Inbox.
//
- (id) defaultFolder
{
  return _folder;
}


//
// This method will always return nil if theName is not
// equal to Inbox (case-insensitive) since you cannot
// access an other mailbox (other than Inbox) using the
// POP3 protocol.
//
- (id) folderForName: (NSString *) theName
{
  if ([theName caseInsensitiveCompare: @"Inbox"] == NSOrderedSame)
    {
      return [self defaultFolder];
    }
  
  return nil;
}


//
//
//
- (id) folderForURL: (NSString *) theURL
{
  return [self defaultFolder];
}


//
//
//
- (BOOL) folderForNameIsOpen: (NSString *) theName
{
  if ([theName caseInsensitiveCompare: @"Inbox"] == NSOrderedSame)
    {
      return YES;
    }

  return NO;
}


//
// No other folder is allowed in POP3 other than the Inbox.
// Also, this folder can only hold messages.
//
- (PantomimeFolderType) folderTypeForFolderName: (NSString *) theName
{
  return PantomimeHoldsMessages;
}


//
// POP3 has no concept of folder separator.
//
- (unichar) folderSeparator
{
  return 0;
}


//
//
//
- (void) close
{
  [self sendCommand: POP3_QUIT  arguments: @"QUIT"];
}


//
//
//
- (void) noop
{
  [self sendCommand: POP3_NOOP  arguments: @"NOOP"];
}


//
// In POP3, you are NOT allowed to create a folder.
//
- (void) createFolderWithName: (NSString *) theName 
			 type: (PantomimeFolderFormat) theType
		     contents: (NSData *) theContents
{
}


//
// In POP3, you are NOT allowed to delete a folder.
//
- (void) deleteFolderWithName: (NSString *) theName
{
}


//
// In POP3, you are NOT allowed to rename a folder.
//
- (void) renameFolderWithName: (NSString *) theName
                       toName: (NSString *) theNewName
{
}


//
//
//
- (NSString *) timestamp
{
  return _timestamp;
}


//
// From RFC1939:
//
//   Responses in the POP3 consist of a status indicator and a keyword
//   possibly followed by additional information.  All responses are
//   terminated by a CRLF pair.  Responses may be up to 512 characters
//   long, including the terminating CRLF.  There are currently two status
//   indicators: positive ("+OK") and negative ("-ERR").  Servers MUST
//   send the "+OK" and "-ERR" in upper case.
//
//   Responses to certain commands are multi-line.  In these cases, which
//   are clearly indicated below, after sending the first line of the
//   response and a CRLF, any additional lines are sent, each terminated
//   by a CRLF pair.  When all lines of the response have been sent, a
//   final line is sent, consisting of a termination octet (decimal code
//   046, ".") and a CRLF pair.  If any line of the multi-line response
//   begins with the termination octet, the line is "byte-stuffed" by
//   pre-pending the termination octet to that line of the response.
//   Hence a multi-line response is terminated with the five octets
//   "CRLF.CRLF".  When examining a multi-line response, the client checks
//   to see if the line begins with the termination octet.  If so and if
//   octets other than CRLF follow, the first octet of the line (the
//   termination octet) is stripped away.  If so and if CRLF immediately
//   follows the termination character, then the response from the POP
//   server is ended and the line containing ".CRLF" is not considered
//   part of the multi-line response.
//
- (void) updateRead
{
  id aData;
 
  char *buf;
  NSUInteger count;

  [super updateRead];

  while ((aData = split_lines(_rbuf)))
    {
      buf = (char *)[aData bytes];
      count = [aData length];
      [_responsesFromServer addObject: aData];

      if (count)
	{
	  switch (*buf)
	    {
	    case '.':
	      //
	      // We verify if we must strip the termination octet
	      //
	      if (count > 1)
		{
		  aData = [NSMutableData dataWithData: aData];
		  buf = [aData mutableBytes];
		  memmove(buf, buf+1, count-2);
		  [aData setLength: count-2];
		}
	      else
		{
		  // We are done receiving multi-line response and
		  // we are ready to parse the received bytes. Before
		  // parsing all the received bytes, we remove the
		  // last line added since it corresponds to our
		  // multi-line response terminator.
		  [_responsesFromServer removeLastObject];
		  [self _parseServerOutput];
		  return;
		}
	      break;

	    case '+':
	      //
	      // There's no real way in POP3 to know if we are currently
	      // reading a multi-line response. We assume we are NOT for
	      // some commands.
	      //
	      if (_lastCommand != POP3_CAPA &&
		  _lastCommand != POP3_LIST &&
		  _lastCommand != POP3_TOP &&
		  _lastCommand != POP3_RETR &&
		  _lastCommand != POP3_RETR_AND_INITIALIZE &&
		  _lastCommand != POP3_UIDL &&
		  (count > 2 && strncmp("+OK", buf, 3) == 0))
		{
		  [self _parseServerOutput];
		  return;
		}
	      break;

	    case '-':
	      if (_lastCommand != POP3_TOP &&
		  _lastCommand != POP3_RETR &&
		  _lastCommand != POP3_RETR_AND_INITIALIZE &&
		  (count > 3 && strncmp("-ERR", buf, 4) == 0))
		{
		  [self _parseServerOutput];
		  return;
		}
	      break;
	    }
	}
    }
}

//
// From RFC1939:
//
//   Commands in the POP3 consist of a case-insensitive keyword, possibly
//   followed by one or more arguments.  All commands are terminated by a
//   CRLF pair.  Keywords and arguments consist of printable ASCII
//   characters.  Keywords and arguments are each separated by a single
//   SPACE character.  Keywords are three or four characters long. Each
//   argument may be up to 40 characters long.
//
- (void) sendCommand: (POP3Command) theCommand  arguments: (NSString *) theFormat, ...
{
  CWPOP3QueueObject *aQueueObject;

  //NSLog(@"sendCommand invoked, cmd = %i", theCommand);

  if (theCommand == POP3_EMPTY_QUEUE)
    {
      if ([_queue count])
	{
	  // We dequeue the first inserted command from the queue.
	  aQueueObject = [_queue lastObject];
	}
      else
	{
	  // The queue is empty, we have nothing more to do...
	  return;
	}
    }
  else
    {
      NSString *aString;
      va_list args;
      
      va_start(args, theFormat);
      
      aString = [[NSString alloc] initWithFormat: theFormat  arguments: args];
      
      aQueueObject = [[CWPOP3QueueObject alloc] initWithCommand: theCommand  arguments: aString];
      RELEASE(aString);

      [_queue insertObject: aQueueObject  atIndex: 0];
      RELEASE(aQueueObject);

      //NSLog(@"queue size = %d:", [_queue count]);
      
      // If we had queued commands, we return since we'll eventually
      // dequeue them one by one. Otherwise, we run it immediately.
      if ([_queue count] > 1)
	{
	  //NSLog(@"QUEUED |%@|", aString);
	  return;
	}
    }
  
  //NSLog(@"Sending |%@|", aQueueObject->arguments);
  _lastCommand = aQueueObject->command;

  // We verify if we had queued an indicator to tell us that we were done
  // wrt expunging the POP3 folder.
  if (_lastCommand == POP3_EXPUNGE_COMPLETED)
    {
      [_queue removeObject: [_queue lastObject]];

      POST_NOTIFICATION(PantomimeFolderExpungeCompleted, self, [NSDictionary dictionaryWithObject: _folder  forKey: @"Folder"]); 
      PERFORM_SELECTOR_2(_delegate, @selector(folderExpungeCompleted:), PantomimeFolderExpungeCompleted, _folder, @"Folder");
      return;
    }

  // We send the command to the POP3 server.
  [self writeData: [aQueueObject->arguments dataUsingEncoding: defaultCStringEncoding]];
  [self writeData: CRLF];
}

//
//
//
- (void) startTLS
{
  [self sendCommand: POP3_STLS  arguments: @"STLS"];
}

@end


//
// Private methods
//
@implementation CWPOP3Store (Private)

- (void) _parseAPOP
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "+OK"])
    {
      AUTHENTICATION_COMPLETED(_delegate, @"APOP");
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"APOP");
    }
}


//
//
//
- (void) _parseAUTHORIZATION
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "+OK"])
    {
      NSRange range1, range2;
      
      range1 = [aData rangeOfCString: "<"];
      range2 = [aData rangeOfCString: ">"];
      
      if (range1.length && range2.length)
	{
	  ASSIGN(_timestamp, [[aData subdataWithRange: NSMakeRange(range1.location,range2.location-range1.location+1)] asciiString]);
	}
      
      [self sendCommand: POP3_CAPA  arguments: @"CAPA"];
    }
  else
    {
      // FIXME
      // connectionLost? or should we call [self close]?
    }
}


//
// See RFC2449 for details.
//
- (void) _parseCAPA
{
  NSData *aData;
  NSUInteger i, count;

  count = [_responsesFromServer count];

  for (i = 1; i < count; i++)
    {
      aData = [_responsesFromServer objectAtIndex: i];
      [_capabilities addObject: AUTORELEASE([[NSString alloc] initWithData: aData  encoding: defaultCStringEncoding])];
    }
  
  POST_NOTIFICATION(PantomimeServiceInitialized, self, nil);
  PERFORM_SELECTOR_1(_delegate, @selector(serviceInitialized:), PantomimeServiceInitialized);
}


//
// From RFC1939:
//
// If no argument was given and the POP3 server issues a
// positive response, then the response given is multi-line.
// After the initial +OK, for each message in the maildrop,
// the POP3 server responds with a line containing
// information for that message.  This line is also called a
// "scan listing" for that message.  If there are no
// messages in the maildrop, then the POP3 server responds
// with no scan listings--it issues a positive response
// followed by a line containing a termination octet and a
// CRLF pair.
//
- (void) _parseLIST
{
  CWPOP3Message *aMessage;
  NSUInteger i, idx, count;
  unsigned long size;

  count = [_responsesFromServer count];
  
  for (i = 1; i < count; i++)
    {
      sscanf([[_responsesFromServer objectAtIndex: i] cString], "%lu %lu", (unsigned long*)&idx, &size);
      
      aMessage = [[_folder messages] objectAtIndex: (idx-1)];
      [aMessage setSize: size];
      [aMessage setMessageNumber: i];
    }

  [self sendCommand: POP3_UIDL  arguments: @"UIDL"];
}


//
//
//
- (void) _parseNOOP
{
  // Do what?
}


//
//
//
- (void) _parsePASS
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];
  
  if ([aData hasCPrefix: "+OK"])
    {
      AUTHENTICATION_COMPLETED(_delegate, @"");
    }
  else
    {
      AUTHENTICATION_FAILED(_delegate, @"");
    }
}


//
//
//
- (void) _parseQUIT
{
  // We don't need to do anything special here.
  [super close];
}


//
//
//
- (void) _parseRETR
{
  NSData *aData;
  
  aData = [_responsesFromServer objectAtIndex: 0];

  if ([aData hasCPrefix: "+OK"])
    {
      NSMutableData *aMutableData;
      CWPOP3Message *aMessage;
      NSUInteger count, i;
      unsigned idx;

      // We get the idx of the message we are parsing...
      sscanf([((CWPOP3QueueObject *)[_queue lastObject])->arguments cString], "RETR %u", &idx);

      aMessage = (CWPOP3Message *)[_folder messageAtIndex: (idx-1)];
      aMutableData = [[NSMutableData alloc] initWithCapacity: [aMessage size]];
      count = [_responsesFromServer count];

      for (i = 1; i < count; i++)
	{
	  [aMutableData appendData: [_responsesFromServer objectAtIndex: i]];

	  // We do NOT append the last \n.
	  if (i < count-1)
	    {
	      [aMutableData appendBytes: "\n"  length: 1];
	    }
	}

      [aMessage setRawSource: aMutableData];

      if (_lastCommand == POP3_RETR_AND_INITIALIZE)
	{
	  NSRange aRange;
	  
	  aRange = [aMutableData rangeOfCString: "\n\n"];
	  
	  if (aRange.length == 0)
	    {
	      [aMessage setInitialized: NO];
	    }
	  else
	    {
	      [aMessage setHeadersFromData: [aMutableData subdataWithRange: NSMakeRange(0,aRange.location)]];
	      [CWMIMEUtility setContentFromRawSource:
			       [aMutableData subdataWithRange:
					       NSMakeRange(aRange.location + 2, [aMutableData length]-(aRange.location+2))]
			     inPart: aMessage];
	      [aMessage setInitialized: YES];
	    }
	}
      
      [aMessage setSize: [aMutableData length]];
      RELEASE(aMutableData);

      // Do that in parse top also?
      if ([_folder cacheManager])
	{
	  cache_record r;

	  r.date = (uint32_t)round([[aMessage receivedDate] timeIntervalSince1970]);
	  r.pop3_uid = [aMessage UID];
	  [(CWPOP3CacheManager *)[_folder cacheManager] writeRecord: &r];
	}

      POST_NOTIFICATION(PantomimeMessagePrefetchCompleted, self, [NSDictionary dictionaryWithObject: aMessage  forKey: @"Message"]);
      PERFORM_SELECTOR_2(_delegate, @selector(messagePrefetchCompleted:), PantomimeMessagePrefetchCompleted, aMessage, @"Message");
    }
}


//
//
//
- (void) _parseSTAT
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "+OK"])
    {
      CWPOP3Message *aMessage;
      int count;
      long size;

      sscanf([aData cString], "+OK %i %li", &count, &size);
      //NSLog(@"count = %d  size = %li", count, size);

      while (count--)
	{
	  aMessage = [[CWPOP3Message alloc] init];
	  [aMessage setFolder: _folder];
	  [[_folder messages] addObject: aMessage];
	  RELEASE(aMessage);
	}

      //NSLog(@"Folder count = %d", [_folder count]);

      [self sendCommand: POP3_LIST  arguments: @"LIST"];
    }
  else
    {
      // FIXME: Do what in case STAT failed?
    }
}

//
//
//
- (void) _parseSTLS
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "+OK"])
    {
      [(CWTCPConnection *)_connection startSSL];

      POST_NOTIFICATION(PantomimeServiceInitialized, self, nil);
      PERFORM_SELECTOR_1(_delegate, @selector(serviceInitialized:), PantomimeServiceInitialized);
    }
  else
    {
      // FIXME: Handle the case where STLS failed
    }
}

//
// This method is very similar to the _parseRETR method.
// We don't touch the message's size (set in _parseLIST)
// since we must know how much we had to read,
//
- (void) _parseTOP
{
  NSData *aData;
  
  aData = [_responsesFromServer objectAtIndex: 0];

  if ([aData hasCPrefix: "+OK"])
    {
      NSMutableData *aMutableData;
      CWPOP3Message *aMessage;
      NSUInteger i, count;
      int idx, num;

      // We get the idx of the message we are parsing...
      sscanf([((CWPOP3QueueObject *)[_queue lastObject])->arguments cString], "TOP %d %d", &idx, &num);

      //NSLog(@"PARTIALLY DECODING MESSAGE no. %d - number of lines %d!", idx, num);
      
      aMessage = (CWPOP3Message *)[_folder messageAtIndex: (idx-1)];
      aMutableData = [[NSMutableData alloc] init];
      count = [_responsesFromServer count];

      for (i = 1; i < count; i++)
	{
	  [aMutableData appendData: [_responsesFromServer objectAtIndex: i]];
	  [aMutableData appendBytes: "\n"  length: 1];
	}

      [aMessage setRawSource: aMutableData];
      RELEASE(aMutableData);

      POST_NOTIFICATION(PantomimeMessagePrefetchCompleted, self, [NSDictionary dictionaryWithObject: aMessage  forKey: @"Message"]);
      PERFORM_SELECTOR_2(_delegate, @selector(messagePrefetchCompleted:), PantomimeMessagePrefetchCompleted, aMessage, @"Message");
    }
}


//
//
//
- (void) _parseUIDL
{
  NSUInteger i, idx, count;
  char buf[71];

  count = [_responsesFromServer count];
  
  for (i = 1; i < count; i++)
    {
       memset(buf, 0, 71);
       sscanf([[_responsesFromServer objectAtIndex: i] cString],"%lu %s", (unsigned long*)&idx, buf);
       [[[_folder messages] objectAtIndex: (idx-1)] setUID: [NSString stringWithCString: buf]];
    }

  POST_NOTIFICATION(PantomimeFolderPrefetchCompleted, self, [NSDictionary dictionaryWithObject: _folder  forKey: @"Folder"]);
  PERFORM_SELECTOR_2(_delegate, @selector(folderPrefetchCompleted:), PantomimeFolderPrefetchCompleted, _folder, @"Folder");
}


//
// From RFC1939:
//
// To authenticate using the USER and PASS command
// combination, the client must first issue the USER
// command.  If the POP3 server responds with a positive
// status indicator ("+OK"), then the client may issue
// either the PASS command to complete the authentication,
// or the QUIT command to terminate the POP3 session.  If
// the POP3 server responds with a negative status indicator
// ("-ERR") to the USER command, then the client may either
// issue a new authentication command or may issue the QUIT
// command.
//
- (void) _parseUSER
{
  NSData *aData;
  
  aData = [_responsesFromServer lastObject];

  if ([aData hasCPrefix: "+OK"])
    {
      [self sendCommand: POP3_PASS  arguments: @"PASS %@", _password];
    }
  else
    {
      // We must terminate the POP3 session.
      [self close];
    }
}


//
//
//
- (void) _parseServerOutput
{
  if (![_responsesFromServer count])
    {
      return;
    }

  //NSLog(@"In _parseServerOutput...%d", _lastCommand);

  switch (_lastCommand)
    {
    case POP3_APOP:
      [self _parseAPOP];
      break;

    case POP3_AUTHORIZATION:
      [self _parseAUTHORIZATION];
      break;

    case POP3_CAPA:
      [self _parseCAPA];
      break;

    case POP3_LIST:
      [self _parseLIST];
      break;
      
    case POP3_NOOP:
      [self _parseNOOP];
      break;

    case POP3_PASS:
      [self _parsePASS];
      break;

    case POP3_QUIT:
      [self _parseQUIT];
      break;

    case POP3_RETR:
    case POP3_RETR_AND_INITIALIZE:
      [self _parseRETR];
      break;

    case POP3_STAT:
      [self _parseSTAT];
      break;

    case POP3_STLS:
      [self _parseSTLS];
      break;

    case POP3_TOP:
      [self _parseTOP];
      break;

    case POP3_UIDL:
      [self _parseUIDL];
      break;

    case POP3_USER:
      [self _parseUSER];
      break;

    default:
      //NSLog(@"UNKNOWN POP3 LAST COMMAND %d", _lastCommand);
      break;
      // FIXME
    }

  // We are done parsing this entry...
  [_responsesFromServer removeAllObjects];
  
  
  // We remove the last object of the queue, if needed.
  //NSLog(@"Removing oldest command from queue (%d)...", [_queue count]);
  if ([_queue count])
    {
      [_queue removeLastObject];
      [self sendCommand: POP3_EMPTY_QUEUE  arguments: @""];
    }
}

@end