/
Cuis-Network-Protocols.pck.st
2671 lines (2158 loc) · 97.2 KB
/
Cuis-Network-Protocols.pck.st
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
'From Cuis 4.1 of 12 December 2012 [latest update: #1549] on 7 January 2013 at 7:04:33 pm'!
'Description Please enter a description for this package '!
!classDefinition: #FTPConnectionException category: #'Cuis-Network-Protocols'!
Error subclass: #FTPConnectionException
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'FTPConnectionException class' category: #'Cuis-Network-Protocols'!
FTPConnectionException class
instanceVariableNames: ''!
!classDefinition: #HTTPClient category: #'Cuis-Network-Protocols'!
Object subclass: #HTTPClient
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'HTTPClient class' category: #'Cuis-Network-Protocols'!
HTTPClient class
instanceVariableNames: ''!
!classDefinition: #HTTPProgress category: #'Cuis-Network-Protocols'!
Notification subclass: #HTTPProgress
instanceVariableNames: 'total amount'
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'HTTPProgress class' category: #'Cuis-Network-Protocols'!
HTTPProgress class
instanceVariableNames: ''!
!classDefinition: #HTTPSocket category: #'Cuis-Network-Protocols'!
Socket subclass: #HTTPSocket
instanceVariableNames: 'headerTokens headers responseCode'
classVariableNames: 'HTTPBlabEmail HTTPProxyCredentials HTTPProxyExceptions HTTPProxyPort HTTPProxyServer ParamDelimiters'
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'HTTPSocket class' category: #'Cuis-Network-Protocols'!
HTTPSocket class
instanceVariableNames: ''!
!classDefinition: #HTTPSocketSqueak category: #'Cuis-Network-Protocols'!
Object subclass: #HTTPSocketSqueak
instanceVariableNames: ''
classVariableNames: 'HTTPBlabEmail HTTPPort HTTPProxyCredentials HTTPProxyExceptions HTTPProxyPort HTTPProxyServer HTTPRequestHandler'
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'HTTPSocketSqueak class' category: #'Cuis-Network-Protocols'!
HTTPSocketSqueak class
instanceVariableNames: ''!
!classDefinition: #ProtocolClient category: #'Cuis-Network-Protocols'!
Object subclass: #ProtocolClient
instanceVariableNames: 'stream connectInfo lastResponse pendingResponses progressObservers'
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'ProtocolClient class' category: #'Cuis-Network-Protocols'!
ProtocolClient class
instanceVariableNames: ''!
!classDefinition: #POP3Client category: #'Cuis-Network-Protocols'!
ProtocolClient subclass: #POP3Client
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'POP3Client class' category: #'Cuis-Network-Protocols'!
POP3Client class
instanceVariableNames: ''!
!classDefinition: #ProtocolClientError category: #'Cuis-Network-Protocols'!
Error subclass: #ProtocolClientError
instanceVariableNames: 'protocolInstance'
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'ProtocolClientError class' category: #'Cuis-Network-Protocols'!
ProtocolClientError class
instanceVariableNames: ''!
!classDefinition: #LoginFailedException category: #'Cuis-Network-Protocols'!
ProtocolClientError subclass: #LoginFailedException
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'LoginFailedException class' category: #'Cuis-Network-Protocols'!
LoginFailedException class
instanceVariableNames: ''!
!classDefinition: #POP3LoginError category: #'Cuis-Network-Protocols'!
ProtocolClientError subclass: #POP3LoginError
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'POP3LoginError class' category: #'Cuis-Network-Protocols'!
POP3LoginError class
instanceVariableNames: ''!
!classDefinition: #TelnetProtocolClient category: #'Cuis-Network-Protocols'!
ProtocolClient subclass: #TelnetProtocolClient
instanceVariableNames: 'responseCode'
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'TelnetProtocolClient class' category: #'Cuis-Network-Protocols'!
TelnetProtocolClient class
instanceVariableNames: ''!
!classDefinition: #FTPClient category: #'Cuis-Network-Protocols'!
TelnetProtocolClient subclass: #FTPClient
instanceVariableNames: 'dataSocket'
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'FTPClient class' category: #'Cuis-Network-Protocols'!
FTPClient class
instanceVariableNames: ''!
!classDefinition: #SMTPClient category: #'Cuis-Network-Protocols'!
TelnetProtocolClient subclass: #SMTPClient
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'SMTPClient class' category: #'Cuis-Network-Protocols'!
SMTPClient class
instanceVariableNames: ''!
!classDefinition: #TelnetProtocolError category: #'Cuis-Network-Protocols'!
ProtocolClientError subclass: #TelnetProtocolError
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Cuis-Network-Protocols'!
!classDefinition: 'TelnetProtocolError class' category: #'Cuis-Network-Protocols'!
TelnetProtocolError class
instanceVariableNames: ''!
!FTPClient commentStamp: '<historical>' prior: 0!
A minimal FTP client program. Could store all state in inst vars, and use an instance to represent the full state of a connection in progress. But simpler to do all that in one method and have it be a complete transaction.
Always operates in passive mode (PASV). All connections are initiated from client in order to get through firewalls.
See ServerDirectory openFTP, ServerDirectory getFileNamed:, ServerDirectory putFile:named: for examples of use.
See TCP/IP, second edition, by Dr. Sidnie Feit, McGraw-Hill, 1997, Chapter 14, p311.!
!HTTPClient commentStamp: '<historical>' prior: 0!
I'm a facade for doing simple HTTP GET/POST operations like downloading / uploading some content.
For example, I get HTML content for http://www.pharo-project.org web page like this:
HTTPClient httpGet: 'http://www.pharo-project.org'.
HTTPClient httpGetDocument: 'http://www.pharo-project.org'.
When successful, a Stream respectively a MIMEDocument is returned, in case of error, a String is returned.
Or, I can make a application/x-www-form-urlencoded post request to http://intranet.acme.com/login and send form data to the server like this:
(args := Dictionary new)
at: 'username' put: #('john@acme.com');
at: 'password' put: #('secretpassword').
result := HTTPClient httpPostDocument: 'http://intranet.acme.com/login' args: args.
Alternatively, I can do a multipart/formdata post request to http://intranet.acme.com/files and send a file like this:
(args := Dictionary new)
at: 'file' put: (Array with: (MIMEDocument contents: 'This is a test' mimeType: 'text/plain' uri: 'file:///test.txt').
result := HTTPClient httpPostDocument: 'http://intranet.acme.com/files' args: args.
Pay attention, my code is not really good.
<trollmode>
I'm a good example of how not to write code. Turn around, walk away,
fast. I'm fully of bugs.
Somebody at some point thought that HTTP is a simple "hacker with
telnet"-protocol. It's not.
</trollmode>
[COTDC] 3 - Laurent Laffont, Francisco Ortiz Peñaloza, Sven Van Caekenberghe, Philippe Marschall.!
!HTTPProgress commentStamp: '<historical>' prior: 0!
A notification to show progress when using HTTP.
I include
- total: The total size of the download (if known)
- amount: The completed amount of the download (if known)
!
!HTTPSocket commentStamp: '<historical>' prior: 0!
HTTPSockets support HTTP requests, either directly or via an HTTP proxy server. An HTTPSocket saves the parse of the last ASCII header it saw, to avoid having to parse it repeatedly.
The real action is in httpGet:accept:. See the examples in the class, especially httpFileInNewChangeSet: and httpShowGif:.!
!HTTPSocketSqueak commentStamp: 'ar 7/10/2010 14:05' prior: 0!
HTTPSockets is a facade for handling common HTTP requests. It provides a minimal implementation of the HTTP protocol, but can be extended by third party clients that register themselves as #httpRequestHandler (see class-side protocol).
A third-party request handler needs to implement the single method
#httpRequest:url:headers:content:response:
in a way that is compatible with the baseline implementation in HTTPSocket.
!
!LoginFailedException commentStamp: '<historical>' prior: 0!
Exception for signaling login failures of protocol clients.
!
!POP3Client commentStamp: '<historical>' prior: 0!
This class implements POP3 (Post Office Protocol 3) as specified in RFC 1939. (see http://www.ietf.org/rfc.html)
You can use it to download email from the mail server to your personal mail program.
To see an example of it's use, see POPSocket class>>example.!
!POP3LoginError commentStamp: '<historical>' prior: 0!
Exception for signaling POP3 login failures.!
!ProtocolClient commentStamp: '<historical>' prior: 0!
ProtocolClient is the abstract super class for a variety of network protocol clients.
It uses a stream rather than the direct network access so it could also work for streams on serial connections etc.
Structure:
stream stream representing the connection to and from the server
connectInfo information required for opening a connection
lastResponse remembers the last response from the server.
progressObservers any object understanding #show: can be registered as a progress observer (login, transfer, etc)!
!ProtocolClientError commentStamp: '<historical>' prior: 0!
Abstract super class for protocol clients
protocolInstance reference to the protocol client throughing the exception. Exception handlers can access the client in order close, respond or whatever may be appropriate
!
!SMTPClient commentStamp: '<historical>' prior: 0!
This class implements the SMTP (mail sending) protocol specified in RFC 821.
HELO <SP> <domain> <CRLF>
MAIL <SP> FROM:<reverse-path> <CRLF>
RCPT <SP> TO:<forward-path> <CRLF>
DATA <CRLF>
RSET <CRLF>
SEND <SP> FROM:<reverse-path> <CRLF>
SOML <SP> FROM:<reverse-path> <CRLF>
SAML <SP> FROM:<reverse-path> <CRLF>
VRFY <SP> <string> <CRLF>
EXPN <SP> <string> <CRLF>
HELP [<SP> <string>] <CRLF>
NOOP <CRLF>
QUIT <CRLF>
TURN <CRLF>
!
!TelnetProtocolClient commentStamp: '<historical>' prior: 0!
Abstract super class for protocol clients based on the generic telnet protocol "<response code> <response>"
Structure:
responseCode the numerical (integer) value of the last response code
!
!TelnetProtocolError commentStamp: '<historical>' prior: 0!
Abstract super class for exceptions signalled by clients based on the telnet protocol.
!
!FTPClient methodsFor: 'protocol' stamp: 'mir 2/13/2002 18:05'!
abortDataConnection
self sendCommand: 'ABOR'.
self closeDataSocket! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 3/7/2002 13:36'!
ascii
self sendCommand: 'TYPE A'.
self lookForCode: 200! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 3/7/2002 13:36'!
binary
self sendCommand: 'TYPE I'.
self lookForCode: 200! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/13/2002 17:52'!
changeDirectoryTo: newDirName
self sendCommand: 'CWD ' , newDirName.
self checkResponse.
! !
!FTPClient methodsFor: 'private' stamp: 'mir 2/19/2002 18:27'!
closeDataSocket
self dataSocket
ifNotNil: [
self dataSocket closeAndDestroy.
self dataSocket: nil]
! !
!FTPClient methodsFor: 'private' stamp: 'mir 10/31/2000 16:24'!
dataSocket
^dataSocket! !
!FTPClient methodsFor: 'private' stamp: 'mir 10/31/2000 18:23'!
dataSocket: aSocket
dataSocket := aSocket! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 17:11'!
deleteDirectory: dirName
self sendCommand: 'RMD ' , dirName.
self checkResponse.
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 17:12'!
deleteFileNamed: fileName
self sendCommand: 'DELE ' , fileName.
self checkResponse.
! !
!FTPClient methodsFor: 'private protocol' stamp: 'svp 10/28/2003 11:06'!
get: limit dataInto: dataStream
"Reel in data until the server closes the connection or the limit is reached.
At the same time, watch for errors on otherSocket."
| buf bytesRead currentlyRead |
currentlyRead := 0.
buf := String new: 4000.
[currentlyRead < limit and:
[self dataSocket isConnected or: [self dataSocket dataAvailable]]]
whileTrue: [
self checkForPendingError.
bytesRead := self dataSocket receiveDataWithTimeoutInto: buf.
1 to: (bytesRead min: (limit - currentlyRead)) do: [:ii | dataStream nextPut: (buf at: ii)].
currentlyRead := currentlyRead + bytesRead].
dataStream reset. "position: 0."
^ dataStream! !
!FTPClient methodsFor: 'private protocol' stamp: 'mir 2/13/2002 18:06'!
getData
| dataStream |
dataStream := RWBinaryOrTextStream on: (String new: 4000).
self getDataInto: dataStream.
self closeDataSocket.
^dataStream contents
! !
!FTPClient methodsFor: 'private protocol' stamp: 'svp 10/28/2003 11:04'!
getDataInto: dataStream
"Reel in all data until the server closes the connection. At the same time, watch for errors on otherSocket. Don't know how much is coming. Put the data on the stream."
| buf bytesRead |
buf := String new: 4000.
[self dataSocket isConnected or: [self dataSocket dataAvailable]]
whileTrue: [
self checkForPendingError.
bytesRead := self dataSocket receiveDataWithTimeoutInto: buf.
1 to: bytesRead do: [:ii | dataStream nextPut: (buf at: ii)]].
dataStream reset. "position: 0."
^ dataStream! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 2/20/2002 13:53'!
getDirectory
| dirList |
self openPassiveDataConnection.
self sendCommand: 'LIST'.
dirList := self getData.
self checkResponse.
self checkResponse.
^dirList
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 16:50'!
getFileList
| dirList |
self openPassiveDataConnection.
self sendCommand: 'NLST'.
dirList := self getData.
self checkResponse.
self checkResponse.
^dirList
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 19:23'!
getFileNamed: remoteFileName
| data |
self openPassiveDataConnection.
self sendCommand: 'RETR ', remoteFileName.
[self checkResponse]
on: TelnetProtocolError
do: [:ex |
self closeDataSocket.
ex pass].
data := self getData.
self checkResponse.
^data
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 5/9/2003 15:50'!
getFileNamed: remoteFileName into: dataStream
self openPassiveDataConnection.
self sendCommand: 'RETR ', remoteFileName.
[self checkResponse]
on: TelnetProtocolError
do: [:ex |
self closeDataSocket.
ex pass].
self getDataInto: dataStream.
self closeDataSocket.
self checkResponse! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 10/31/2000 19:03'!
getPartial: limit fileNamed: remoteFileName into: dataStream
| data |
self openPassiveDataConnection.
self sendCommand: 'RETR ', remoteFileName.
[self checkResponse]
on: TelnetProtocolError
do: [:ex |
self closeDataSocket.
ex pass].
data := self get: limit dataInto: dataStream.
self abortDataConnection.
^data
! !
!FTPClient methodsFor: 'private' stamp: 'mir 4/7/2003 17:20'!
login
self user ifNil: [^self].
["repeat both USER and PASS since some servers require it"
self sendCommand: 'USER ', self user.
"331 Password required"
self lookForCode: 331.
"will ask user, if needed"
self sendCommand: 'PASS ', self password.
"230 User logged in"
([self lookForCode: 230.]
on: TelnetProtocolError
do: [false]) == false
] whileTrue: [
(LoginFailedException protocolInstance: self) signal: self lastResponse]
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/12/2002 18:39'!
loginUser: userName password: passwdString
self user: userName.
self password: passwdString.
self login! !
!FTPClient methodsFor: 'private protocol' stamp: 'LucFabresse 11/2/2010 22:10'!
lookForCode: code ifDifferent: handleBlock
"We are expecting a certain numeric code next.
However, in the FTP protocol, multiple lines are allowed.
If the response is multi-line, the fourth character of the first line is a
$- and the last line repeats the numeric code but the code is followed by
a space. So it's possible that there are more lines left of the last response that
we need to throw away. We use peekForAll: so that we don't discard the
next response that is not a continuation line."
"check for multi-line response"
(self lastResponse size > 3
and: [(self lastResponse at: 4) = $-])
ifTrue: ["Discard continuation lines."
| headToDiscard |
headToDiscard := self lastResponse first: 4.
[[self stream peekForAll: headToDiscard]
whileTrue: [self stream nextLine]]
on: Exception
do: [:ex | ^handleBlock value: nil]].
^ super lookForCode: code ifDifferent: handleBlock! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 17:10'!
makeDirectory: newDirName
self sendCommand: 'MKD ' , newDirName.
self checkResponse.
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/14/2002 17:51'!
openDataSocket: remoteHostAddress port: dataPort
dataSocket := Socket new.
dataSocket connectTo: remoteHostAddress port: dataPort! !
!FTPClient methodsFor: 'private protocol' stamp: 'michael.rueger 6/16/2009 11:28'!
openPassiveDataConnection
| portInfo list dataPort remoteHostAddress remoteAddressString |
self sendCommand: 'PASV'.
self lookForCode: 227 ifDifferent: [:response | (TelnetProtocolError protocolInstance: self) signal: 'Could not enter passive mode: ' , response].
portInfo := (self lastResponse findTokens: '()') at: 2.
list := portInfo findTokens: ','.
remoteHostAddress := ByteArray
with: (list at: 1) asNumber
with: (list at: 2) asNumber
with: (list at: 3) asNumber
with: (list at: 4) asNumber.
remoteAddressString := String streamContents: [:addrStream | remoteHostAddress
do: [ :each | each printOn: addrStream ]
separatedBy: [ addrStream nextPut: $. ]].
dataPort := (list at: 5) asNumber * 256 + (list at: 6) asNumber.
self openDataSocket: (NetNameResolver addressForName: remoteAddressString) port: dataPort! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/14/2002 16:55'!
passive
self sendCommand: 'PASV'.
self lookForCode: 227! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/19/2002 16:54'!
putFileNamed: filePath as: fileNameOnServer
"FTP a file to the server."
| fileStream |
fileStream := FileStream readOnlyFileNamed: filePath.
fileStream
ifNil: [(FileDoesNotExistException fileName: filePath) signal].
self putFileStreamContents: fileStream as: fileNameOnServer
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 12/8/2003 16:54'!
putFileStreamContents: fileStream as: fileNameOnServer
"FTP a file to the server."
self openPassiveDataConnection.
self sendCommand: 'STOR ', fileNameOnServer.
fileStream reset.
[self sendStreamContents: fileStream]
ensure: [self closeDataSocket].
self checkResponse.
self checkResponse.
! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/14/2002 16:43'!
pwd
| result |
self sendCommand: 'PWD'.
self lookForCode: 257.
result := self lastResponse.
^result copyFrom: (result indexOf: $")+1 to: (result lastIndexOf: $")-1! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 10/31/2000 13:12'!
quit
self sendCommand: 'QUIT'.
self close! !
!FTPClient methodsFor: 'protocol' stamp: 'mir 11/13/2002 17:50'!
removeFileNamed: remoteFileName
self sendCommand: 'DELE ', remoteFileName.
self checkResponse.
! !
!FTPClient methodsFor: 'protocol' stamp: 'nk 1/26/2005 16:40'!
renameFileNamed: oldFileName to: newFileName
self sendCommand: 'RNFR ' , oldFileName.
self lookForCode: 350.
self sendCommand: 'RNTO ' , newFileName.
self lookForCode: 250! !
!FTPClient methodsFor: 'private' stamp: 'mir 11/14/2002 18:14'!
sendStreamContents: aStream
self dataSocket sendStreamContents: aStream checkBlock: [self checkForPendingError. true]! !
!FTPClient class methodsFor: 'accessing' stamp: 'mir 10/30/2000 20:10'!
defaultPortNumber
^21! !
!FTPClient class methodsFor: 'accessing' stamp: 'mir 2/25/2002 19:08'!
logFlag
^#ftp! !
!FTPClient class methodsFor: 'accessing' stamp: 'mir 2/13/2002 17:50'!
rawResponseCodes
#(200 'Command okay.'
500 'Syntax error, command unrecognized. This may include errors such as command line too long.'
501 'Syntax error in parameters or arguments.'
202 'Command not implemented, superfluous at this site.'
502 'Command not implemented.'
503 'Bad sequence of commands.'
504 'Command not implemented for that parameter.'
110 'Restart marker reply. In this case, the text is exact and not left to the particular implementation; it must read: MARK yyyy = mmmm Where yyyy is User-process data stream marker, and mmmm server''s equivalent marker (note the spaces between markers and "=").'
211 'System status, or system help reply.'
212 'Directory status.'
213 'File status.'
214 'Help message. On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.'
215 'NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document.'
120 'Service ready in nnn minutes.'
220 'Service ready for new user.'
221 'Service closing control connection. Logged out if appropriate.'
421 'Service not available, closing control connection. This may be a reply to any command if the service knows it must shut down.'
125 'Data connection already open; transfer starting.'
225 'Data connection open; no transfer in progress.'
425 'Can''t open data connection.'
226 'Closing data connection. Requested file action successful (for example, file transfer or file abort).'
426 'Connection closed; transfer aborted.'
227 'Entering Passive Mode (h1,h2,h3,h4,p1,p2).'
230 'User logged in, proceed.'
530 'Not logged in.'
331 'User name okay, need password.'
332 'Need account for login.'
532 'Need account for storing files.'
150 'File status okay; about to open data connection.'
250 'Requested file action okay, completed.'
257 '"PATHNAME" created.'
350 'Requested file action pending further information.'
450 'Requested file action not taken. File unavailable (e.g., file busy).'
550 'Requested action not taken. File unavailable (e.g., file not found, no access).'
451 'Requested action aborted. Local error in processing.'
551 'Requested action aborted. Page type unknown.'
452 'Requested action not taken. Insufficient storage space in system.'
552 'Requested file action aborted. Exceeded storage allocation (for current directory or dataset).'
553 'Requested action not taken. File name not allowed.')
! !
!FTPConnectionException methodsFor: 'as yet unclassified' stamp: 'RAA 3/9/2001 07:47'!
defaultAction
self resume! !
!FTPConnectionException methodsFor: 'as yet unclassified' stamp: 'RAA 3/14/2001 15:57'!
isResumable
^true! !
!HTTPClient class methodsFor: 'post/get' stamp: 'nk 8/30/2004 07:50'!
httpGet: url
| document |
document := self httpGetDocument: url.
^(document isString)
ifTrue: [
"strings indicate errors"
document]
ifFalse: [(RWBinaryOrTextStream with: document content) reset]! !
!HTTPClient class methodsFor: 'post/get' stamp: 'MarcusDenker 2/23/2010 16:38'!
httpGetDocument: url
^HTTPSocket httpGetDocument: url! !
!HTTPClient class methodsFor: 'post/get' stamp: 'mir 5/1/2001 15:04'!
httpPostDocument: url args: argsDict
^self httpPostDocument: url target: nil args: argsDict! !
!HTTPClient class methodsFor: 'post/get' stamp: 'MarcusDenker 2/23/2010 16:38'!
httpPostDocument: url target: target args: argsDict
^HTTPSocket httpPostDocument: url args: argsDict! !
!HTTPClient class methodsFor: 'post/get' stamp: 'MarcusDenker 2/23/2010 16:39'!
httpPostMultipart: url args: argsDict
" do multipart/form-data encoding rather than x-www-urlencoded "
^HTTPSocket httpPostMultipart: url args: argsDict accept: nil request: ''! !
!HTTPClient class methodsFor: 'post/get' stamp: 'MarcusDenker 2/23/2010 16:40'!
requestURL: url target: target
^FileStream requestURL: url target: target! !
!HTTPClient class methodsFor: 'utilities' stamp: 'mir 2/2/2001 17:59'!
uploadFileNamed: aFilename to: baseUrl user: user passwd: passwd
| fileContents remoteFilename |
remoteFilename := (baseUrl endsWith: '/')
ifTrue: [baseUrl , '/' , aFilename]
ifFalse: [baseUrl , aFilename].
fileContents := (StandardFileStream readOnlyFileNamed: aFilename) contentsOfEntireFile.
HTTPSocket httpPut: fileContents to: remoteFilename user: user passwd: passwd! !
!HTTPProgress methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:28'!
amount
"Answer the value of amount"
^ amount! !
!HTTPProgress methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:28'!
amount: anObject
"Set the value of amount"
amount := anObject! !
!HTTPProgress methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:28'!
total
"Answer the value of total"
^ total! !
!HTTPProgress methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:28'!
total: anObject
"Set the value of total"
total := anObject! !
!HTTPSocket methodsFor: 'accessing' stamp: 'SvenVanCaekenberghe 1/8/2012 14:44'!
contentType
| type i |
type := self getHeader: 'content-type' default: nil.
type ifNil: [ ^nil ].
type := type trimBoth.
i := type indexOf: $;.
i = 0 ifTrue: [ ^type ].
^(type copyFrom: 1 to: i-1) trimBoth ! !
!HTTPSocket methodsFor: 'accessing' stamp: 'dc 10/21/2008 08:49'!
contentType: header
"extract the content type from the header. Content-type: text/plain<cr><lf>, User may look in headerTokens afterwards."
| this |
headerTokens ifNil: [ headerTokens := header findTokens: ParamDelimiters keep: String cr].
1 to: headerTokens size do: [:ii |
this := headerTokens at: ii.
(this first asLowercase = $c and: [#('content-type:' 'content type') includes: this asLowercase]) ifTrue: [
^ (headerTokens at: ii+1)]].
^ nil "not found"! !
!HTTPSocket methodsFor: 'accessing' stamp: 'dc 10/21/2008 08:49'!
contentsLength: header
"extract the data length from the header. Content-length: 1234<cr><lf>, User may look in headerTokens afterwards."
| this |
headerTokens := header findTokens: ParamDelimiters keep: String cr.
1 to: headerTokens size do: [:ii |
this := headerTokens at: ii.
(this first asLowercase = $c and: [this asLowercase = 'content-length:']) ifTrue: [
^ (headerTokens at: ii+1) asNumber]].
^ nil "not found"! !
!HTTPSocket methodsFor: 'accessing' stamp: 'adrian-lienhard 6/5/2009 22:00'!
getHeader: name
^self getHeader: name default: nil! !
!HTTPSocket methodsFor: 'accessing' stamp: 'adrian-lienhard 6/5/2009 22:01'!
getHeader: name default: defaultValue
^headers at: name ifAbsent: [defaultValue]! !
!HTTPSocket methodsFor: 'receiving' stamp: 'asasa 8/31/2010 20:41'!
getResponseUpTo: markerString
"Keep reading until the marker is seen. Return three parts: header, marker, beginningOfData. Fails if no marker in first 2000 chars."
| buf position bytesRead tester mm tries |
buf := String new: 2000.
position := 0.
tester := 1. mm := 1.
tries := 3.
[tester := tester - markerString size + 1 max: 1. "rewind a little, in case the marker crosses a read boundary"
tester to: position do: [:tt |
(buf at: tt) = (markerString at: mm) ifTrue: [mm := mm + 1] ifFalse: [mm := 1].
"Not totally correct for markers like xx0xx"
mm > markerString size ifTrue: ["got it"
^ Array with: (buf copyFrom: 1 to: tt+1-mm)
with: markerString
with: (buf copyFrom: tt+1 to: position)]].
tester := 1 max: position. "OK if mm in the middle"
(position < buf size) & (self isConnected | self dataAvailable)
& ((tries := tries - 1) >= 0)] whileTrue: [
self waitForDataFor: 5 ifClosed: [
Transcript show: ' <connection closed> ']
ifTimedOut: [
Transcript show: ' <response was late> '].
bytesRead := self primSocket: socketHandle receiveDataInto: buf
startingAt: position + 1 count: buf size - position.
position := position + bytesRead].
^ Array with: (buf copyFrom: 1 to: position)
with: ''
with: '' "Marker not found and connection closed".
! !
!HTTPSocket methodsFor: 'receiving' stamp: 'PeterHugossonMiller 9/3/2009 01:58'!
getResponseUpTo: markerString ignoring: ignoreString
"Keep reading, until the marker is seen, skipping characters in ignoreString when
comparing to the marker. Return three parts: header, marker, beginningOfData.
Fails if no marker in first 2000 chars."
| buf position bytesRead tester mm skipped |
buf := String new: 2000.
position := 0.
tester := 1. mm := 1.
skipped := 0.
[tester := tester - markerString size + 1 max: 1. "rewind a little, in case the marker crosses a read boundary"
tester to: position do: [:tt |
(buf at: tt) = (markerString at: mm) ifFalse:
[[ignoreString includes: (markerString at: mm)] whileTrue:
[mm := mm + 1. skipped := skipped + 1]].
(buf at: tt) = (markerString at: mm)
ifTrue: [mm := mm + 1]
ifFalse: [mm := 1. skipped := 0].
"Not totally correct for markers like xx0xx"
mm > markerString size ifTrue: ["got it"
^ Array with: (buf copyFrom: 1 to: tt+1-mm+skipped)
with: markerString
with: (buf copyFrom: tt+1 to: position)]].
tester := 1 max: position. "OK if mm in the middle"
(position < buf size) & (self isConnected | self dataAvailable)] whileTrue: [
self waitForDataFor: 5 ifClosed: [
Transcript show: ' <connection closed> ']
ifTimedOut: [
Transcript show: 'data was late'].
bytesRead := self primSocket: socketHandle receiveDataInto: buf
startingAt: position + 1 count: buf size - position.
position := position + bytesRead].
^ Array with: (buf copyFrom: 1 to: position)
with: ''
with: '' "Marker not found and connection closed".
! !
!HTTPSocket methodsFor: 'receiving' stamp: 'adrian-lienhard 6/5/2009 22:34'!
getRestOfBuffer: beginning
"We don't know the length. Keep going until connection is closed. Part of it has already been received. Response is of type text, not binary."
| buf response bytesRead |
response := RWBinaryOrTextStream on: (String new: 2000).
response nextPutAll: beginning.
buf := String new: 2000.
[self isConnected | self dataAvailable]
whileTrue: [
self waitForDataFor: 5 ifClosed: [
Transcript show: ' <connection closed> ']
ifTimedOut: [
Transcript show: 'data was slow'].
bytesRead := self primSocket: socketHandle receiveDataInto: buf
startingAt: 1 count: buf size.
bytesRead > 0 ifTrue: [
response nextPutAll: (buf copyFrom: 1 to: bytesRead)] ].
response reset. "position: 0."
^ response
! !
!HTTPSocket methodsFor: 'receiving' stamp: 'StephaneDucasse 3/28/2010 21:29'!
getRestOfBuffer: beginning totalLength: length
"Reel in a string of a fixed length. Part of it has already been received. Close the connection after all chars are received. We do not strip out linefeed chars. tk 6/16/97 22:32"
"if length is nil, read until connection close. Response is of type text, not binary."
| buf response bytesRead |
length ifNil: [^ self getRestOfBuffer: beginning].
buf := String new: length.
response := RWBinaryOrTextStream on: buf.
response nextPutAll: beginning.
buf := String new: length.
[(response position < length) & (self isConnected | self dataAvailable)]
whileTrue: [
(HTTPProgress new)
total: length;
amount: response position;
signal: 'Downloading...'.
self waitForDataFor: 5 ifClosed: [
Transcript show: ' <connection closed> ']
ifTimedOut: [
Transcript show: 'data was slow'].
bytesRead := self primSocket: socketHandle receiveDataInto: buf startingAt: 1
count: (length - response position).
bytesRead > 0 ifTrue: [
response nextPutAll: (buf copyFrom: 1 to: bytesRead)] ].
"Transcript cr; show: 'data byte count: ', response position printString."
"Transcript cr; show: ((self isConnected) ifTrue: ['Over length by: ', bytesRead printString]
ifFalse: ['Socket closed'])."
response position < length ifTrue: [^ 'server aborted early'].
response reset. "position: 0."
^ response! !
!HTTPSocket methodsFor: 'accessing' stamp: 'SvenVanCaekenberghe 1/8/2012 14:45'!
header: headerText
"set the headers. Then getHeader: can be used"
"divide into basic lines"
| lines foldedLines statusLine |
lines := headerText findTokens: String crlf.
statusLine := lines first.
lines := lines copyFrom: 2 to: lines size.
"parse the status (pretty trivial right now)"
responseCode := (statusLine findTokens: ' ') second.
"fold lines that start with spaces into the previous line"
foldedLines := OrderedCollection new.
lines do: [ :line |
line first isSeparator ifTrue: [
foldedLines at: foldedLines size put: (foldedLines last, line) ]
ifFalse: [ foldedLines add: line ] ].
"make a dictionary mapping headers to header contents"
headers := Dictionary new.
foldedLines do: [ :line | | i |
i := line indexOf: $:.
i > 0 ifTrue: [
headers
at: (line copyFrom: 1 to: i-1) asLowercase
put: (line copyFrom: i+1 to: line size) trimBoth ] ].
! !
!HTTPSocket methodsFor: 'receiving' stamp: 'adrian-lienhard 6/5/2009 22:02'!
redirect
"See if the header has a 'Location: url CrLf' in it. If so, return the new URL of this page. tk 6/24/97 18:03"
| this |
1 to: headerTokens size do: [:ii |
this := headerTokens at: ii.
(this first asLowercase = $l and: [this asLowercase = 'location:']) ifTrue: [
^ (headerTokens at: ii+1)]].
^ nil "not found"
! !
!HTTPSocket methodsFor: 'accessing' stamp: 'ls 8/12/1998 00:41'!
responseCode
^responseCode! !
!HTTPSocket methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:43'!
sendCommandWithProgress: commandString
"Send the given command as a single line followed by a <CR><LF> terminator."
self sendDataWithProgress: commandString, String crlf.
! !
!HTTPSocket methodsFor: 'accessing' stamp: 'StephaneDucasse 3/28/2010 21:46'!
sendDataWithProgress: aStringOrByteArray
"Send all of the data in the given array, even if it requires multiple calls to send it all. Return the number of bytes sent."
"An experimental version use on slow lines: Longer timeout and smaller writes to try to avoid spurious timeouts."
| bytesSent bytesToSend count |
bytesToSend := aStringOrByteArray size.
bytesSent := 0.
[bytesSent < bytesToSend] whileTrue: [
"superclass code should probably offer a hook - sd"
(HTTPProgress new)
total: bytesToSend;
amount: bytesSent;
signal: 'Uploading...'.
(self waitForSendDoneFor: 60)
ifFalse: [ConnectionTimedOut signal: 'send data timeout; data not sent'].
count := self primSocket: socketHandle
sendData: aStringOrByteArray
startIndex: bytesSent + 1
count: (bytesToSend - bytesSent min: 5000).
bytesSent := bytesSent + count].
^ bytesSent
! !
!HTTPSocket class methodsFor: 'proxy settings' stamp: 'mir 7/30/1999 16:08'!
addProxyException: domainName
"Add a (partial, wildcard) domain name to the list of proxy exceptions"
"HTTPSocket addProxyException: '*.online.disney.com'"
self httpProxyExceptions add: domainName! !
!HTTPSocket class methodsFor: 'utilities' stamp: 'PeterHugossonMiller 9/3/2009 01:44'!
argString: args
"Return the args in a long string, as encoded in a url"
| argsString first |
args isString ifTrue: ["sent in as a string, not a dictionary"
^ (args first = $? ifTrue: [''] ifFalse: ['?']), args].
argsString := String new writeStream.
argsString nextPut: $?.
first := true.
args associationsDo: [ :assoc |
assoc value do: [ :value |
first ifTrue: [ first := false ] ifFalse: [ argsString nextPut: $& ].
argsString nextPutAll: assoc key encodeForHTTP.
argsString nextPut: $=.
argsString nextPutAll: value encodeForHTTP. ] ].
^ argsString contents
! !
!HTTPSocket class methodsFor: 'utilities' stamp: 'PeterHugossonMiller 9/3/2009 01:44'!
argStringUnencoded: args
"Return the args in a long string, as encoded in a url"
| argsString first |
args isString ifTrue: ["sent in as a string, not a dictionary"
^ (args first = $? ifTrue: [''] ifFalse: ['?']), args].
argsString := String new writeStream.
argsString nextPut: $?.
first := true.
args associationsDo: [ :assoc |