File: FTP.st

package info (click to toggle)
gnu-smalltalk 2.1.8-2.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 17,484 kB
  • ctags: 8,274
  • sloc: ansic: 53,661; sh: 17,366; perl: 4,319; awk: 1,319; yacc: 1,023; makefile: 1,010; sed: 258; lex: 249
file content (513 lines) | stat: -rw-r--r-- 14,687 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
"======================================================================
|
|   FTP protocol support
|
|
 ======================================================================"


"======================================================================
|
| Based on code copyright (c) Kazuki Yasumatsu, and in the public domain
| Copyright (c) 2002 Free Software Foundation, Inc.
| Adapted by Paolo Bonzini.
|
| This file is part of the GNU Smalltalk class library.
|
| The GNU Smalltalk class 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, or (at
| your option) any later version.
|
| The GNU Smalltalk class 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 Lesser General Public License
| along with the GNU Smalltalk class library; see the file COPYING.LIB.
| If not, write to the Free Software Foundation, 59 Temple Place - Suite
| 330, Boston, MA 02111-1307, USA.
|
 ======================================================================"


Namespace current: NetClients.FTP!

Object subclass:  #FTPServerEntity
	instanceVariableNames: 'permissions id owner group sizeInBytes modifiedDate filename isDirectory '
	classVariableNames: ''
	poolDictionaries: ''
	category: 'NetClients-FTP'!

FTPServerEntity comment: 
nil!

NetClient subclass:  #FTPClient
	instanceVariableNames: 'loggedInUser'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'NetClients-FTP'!

FTPClient comment: 
'
Copyright (c) Kazuki Yasumatsu, 1995. All rights reserved.
'!

NetProtocolInterpreter subclass:  #FTPProtocolInterpreter
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: 'TCP'
	category: 'NetClients-FTP'!

FTPClient comment: 
'
Copyright (c) Kazuki Yasumatsu, 1995. All rights reserved.
'!

NetClientError subclass:  #FTPFileNotFoundError
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'NetClients-FTP'!

FTPFileNotFoundError comment: 
nil!


!FTPServerEntity methodsFor: 'accessing'!

filename
    ^filename!

filename: aValue
    filename := aValue!

group
    ^group!

group: aValue
    group := aValue!

id
    ^id!

id: aValue
    id := aValue asNumber!

isDirectory
    ^isDirectory!

isDirectory: aValue
    isDirectory := aValue!

modifiedDate
    ^modifiedDate!

modifiedDate: aValue
    modifiedDate := aValue!

owner
    ^owner!

owner: aValue
    owner := aValue!

permissions
    ^permissions!

permissions: aValue
    permissions := aValue!

sizeInBytes
    ^sizeInBytes!

sizeInBytes: aValue
    sizeInBytes := aValue asNumber! !

!FTPServerEntity methodsFor: 'displaying'!

displayString
    | stream |
    stream := Stream on: (String new: 100).
    self isDirectory
    	ifTrue: [stream nextPutAll: ' <D> ' ]
    	ifFalse: [stream space: 5].
    stream nextPutAll: self filename; space: 30 - self filename size.
    stream nextPutAll: self sizeInBytes printString.
    ^stream contents! !

!FTPServerEntity methodsFor: 'initialize-release'!

from: stream
    self permissions: (stream upTo: Character space).
    stream skipSeparators. 
    self id: (stream upTo: Character space).
    stream skipSeparators.
    self owner:  (stream upTo: Character space).
    stream skipSeparators.
    self group: (stream upTo: Character space).
    stream skipSeparators. 
    self sizeInBytes: (stream upTo: Character space).
    stream skipSeparators. 
    self modifiedDate: (self getDateFromNext: 3 on: stream). 
    stream skipSeparators.
    self filename: (stream upTo: Character space). 
    self isDirectory: (self sizeInBytes = 0).! !

!FTPServerEntity methodsFor: 'private'!

getDateFromNext: aNumber on: stream
    | iStream |
    iStream := WriteStream on: (String new: 100).
    aNumber timesRepeat:
    	[iStream nextPutAll: (stream upTo: Character space).
    	iStream nextPut: Character space.
    		stream skipSeparators].
    ^DateTime readFrom: iStream contents readStream! !




!FTPClient class methodsFor: 'examples'!

exampleHost: host
    "self exampleHost: 'localhost'."

    ^self exampleHost: host port: 21!

exampleHost: host port: port
    "self exampleHost: 'localhost' port: 2121."

    | user password stream client |
    user := 'utente'.
    password := 'bonzini'.
    stream := WriteStream on: (String new: 256).
    client := FTPClient connectToHost: host port: port.
    [client username: user password: password; login; getList: '/' into: stream]
    	ensure: [client close].
    ^stream contents!

exampleHost: host fileName: fileName
    "self exampleHost: 'localhost'."

    ^self exampleHost: host port: 21 fileName: fileName!

exampleHost: host port: port fileName: fileName
    "self exampleHost: 'arrow' fileName: '/pub/smallwalker/README'."

    | user password stream client |
    user := 'utente'.
    password := 'bonzini'.
    stream := WriteStream on: (String new: 256).
    client := FTPClient connectToHost: host port: port.
    [client username: user password: password; login; getFile: fileName type: #ascii into: stream]
    	ensure: [client close].
    ^stream contents! !

!FTPClient methodsFor: 'private'!

protocolInterpreter
    ^FTPProtocolInterpreter! !

!FTPClient methodsFor: 'ftp'!

login
    self connectIfClosed.
    loggedInUser = self user ifTrue: [ ^self ].
    self clientPI ftpUser: self user username.
    self clientPI ftpPassword: self user password.
    loggedInUser := self user.
!

logout
    loggedInUser := nil.
    self clientPI ftpQuit; close
!

getFile: fileName type: type into: aStream
    | fname directory tail |

    self login.

    fname := File name: fileName.
    directory := fname path asString.
    tail := fname stripPath asString.
    tail isEmpty
    	ifTrue:
    		[^self clientPI
    			getDataWithType: type
    			into: aStream
    			do: [self clientPI ftpRetrieve: fileName]]
    	ifFalse:
    		[self clientPI ftpCwd: directory.
    		^self clientPI
    			getDataWithType: type
    			into: aStream
    			do: [self clientPI ftpRetrieve: tail]]!

getList: pathName into: aStream 
    | fname directory tail |

    self login.

    fname := File name: pathName.
    directory := fname path asString.
    tail := fname stripPath asString.
    self clientPI ftpCwd: directory.
    ^self clientPI
    	getDataWithType: #ascii
    	into: aStream
    	do: [tail isEmpty
    			ifTrue:	[self clientPI ftpList]
    			ifFalse: [self clientPI ftpList: tail].
    		0].!

!FTPProtocolInterpreter class methodsFor: 'accessing'!

defaultPortNumber
    ^21! !

!FTPProtocolInterpreter methodsFor: 'data connection'!

openDataConnectionDo: controlBlock
    | portSocket dataStream |
    "Create a socket.  Set up a queue for a single connection."
    portSocket := ServerSocket 
	reuseAddr: true
	port: 0
	queueSize: 1
	bindTo: nil.

    [
        self ftpPort: portSocket port host: portSocket address asByteArray.

        "issue control command."
        controlBlock value.

        [ (dataStream := portSocket accept) isNil ] whileTrue: [ Processor yield ].
    ] ensure: [portSocket close].

    ^dataStream!

openPassiveDataConnectionDo: controlBlock
    | array dataSocket dataStream |
    "Enter Passive Mode"
    array := self ftpPassive.
    
    dataStream := Socket
	remote: (IPAddress fromBytes: (array at: 1))
	port: (array at: 2).

    "issue control command."
    controlBlock value.

    ^dataStream! !

!FTPProtocolInterpreter methodsFor: 'ftp protocol'!

connect
    super connect.
    self checkResponse!

getDataWithType: type into: aStream do: controlBlock
    | dataStream totalByte |
    (#(#ascii #binary) includes: type)
    	ifFalse: [^self error: 'type must be #ascii or #binary'].
    type == #ascii
    	ifTrue:	[self ftpTypeAscii]
    	ifFalse: [self ftpTypeBinary].

    "dataStream := self openDataConnectionDo: [totalByte := controlBlock value]."
    dataStream := self openPassiveDataConnectionDo: [totalByte := controlBlock value].

    totalByte > 0 ifTrue: [self reporter totalByte: totalByte].
    self reporter startTransfer.

    [[dataStream atEnd]
    	whileFalse:
    		[| byte |
    		byte := dataStream nextHunk.
    		self reporter readByte: byte size.
    		type == #ascii
    			ifTrue:	[aStream nextPutAll: (self decode: byte)]
    			ifFalse: [aStream nextPutAll: byte]]
    ] ensure: [dataStream close].

    self reporter endTransfer!

ftpAbort
    self nextPutAll: 'ABOR'; cr.
    self checkResponse!

ftpCdup
    "Change to Parent Directory"

    self nextPutAll: 'CDUP'; cr.
    self checkResponse!

ftpCwd: directory
    "Change Working Directory"

    self nextPutAll: ('CWD ', directory); cr.
    self checkResponse!

ftpList
    self nextPutAll: 'LIST'; cr.
    self checkResponse!

ftpList: pathName
    self nextPutAll: ('LIST ', pathName); cr.
    self checkResponse!

ftpPassive
    | response stream hostAddress port |
    self nextPutAll: 'PASV'; cr.
    response := self getResponse.
    self checkResponse: response.
    response status = 227 ifFalse: [^self protocolError: response statusMessage].

    "227 Entering Passive Mode (h1,h2,h3,h4,p1,p2)"
    stream := response statusMessage readStream.
    hostAddress := ByteArray new: 4.
    stream upTo: $(.
    hostAddress at: 1 put: (Integer readFrom: stream).
    stream skip: 1.
    hostAddress at: 2 put: (Integer readFrom: stream).
    stream skip: 1.
    hostAddress at: 3 put: (Integer readFrom: stream).
    stream skip: 1.
    hostAddress at: 4 put: (Integer readFrom: stream).
    stream skip: 1.
    port := Integer readFrom: stream.
    stream skip: 1.
    port := (port bitShift: 8) + (Integer readFrom: stream).
    ^Array with: hostAddress with: port!

ftpPassword: password
    | response |
    self nextPutAll: ('PASS ', password); cr.
    response := self getResponse.
    self
    	checkResponse: response
    	ifError: [self loginIncorrectError: response statusMessage]!

ftpPort: portInteger host: hostAddressBytes
    self
    	nextPutAll: 'PORT ';
    	nextPutAll: (hostAddressBytes at: 1) printString;
    	nextPut: $,;
    	nextPutAll: (hostAddressBytes at: 2) printString;
    	nextPut: $,;
    	nextPutAll: (hostAddressBytes at: 3) printString;
    	nextPut: $,;
    	nextPutAll: (hostAddressBytes at: 4) printString;
    	nextPut: $,;
    	nextPutAll: ((portInteger bitShift: -8) bitAnd: 16rFF) printString;
    	nextPut: $,;
    	nextPutAll: (portInteger bitAnd: 16rFF) printString;
    	cr.
    self checkResponse!

ftpQuit
    self nextPutAll: 'QUIT'; cr.
    self checkResponse!

ftpRetrieve: fileName
    | response stream |
    self nextPutAll: ('RETR ', fileName); cr.
    response := self getResponse.
    self checkResponse: response.

    "150 Opening data connection for file (398 bytes)."
    stream := response statusMessage readStream.
    stream skipTo: $(.
    stream atEnd ifTrue: [ ^nil ].
    ^Integer readFrom: stream!

ftpStore: fileName
    self nextPutAll: ('STOR ', fileName); cr.
    self checkResponse!

ftpType: type
    self nextPutAll: ('TYPE ', type); cr.
    self checkResponse!

ftpTypeAscii
    ^self ftpType: 'A'!

ftpTypeBinary
    ^self ftpType: 'I'!

ftpUser: user
    self nextPutAll: ('USER ', user); cr.
    self checkResponse! !

!FTPProtocolInterpreter methodsFor: 'private'!

checkResponse: response
    ^self
    	checkResponse: response
    	ifError: [self protocolError: response statusMessage]!

checkResponse: response ifError: errorBlock
    | status |
    status := response status.

    "Positive Preliminary reply"
    status = 110 "Restart marker reply"				ifTrue: [^self].
    status = 120 "Service ready in nnn minutes"			ifTrue: [^self].
    status = 125 "Data connection already open"			ifTrue: [^self].
    status = 150 "File status okay"				ifTrue: [^self].

    "Positive Completion reply"
    status = 200 "OK"						ifTrue: [^self].
    status = 202 "Command not implemented"			ifTrue: [^self].
    status = 211 "System status"				ifTrue: [^self].
    status = 212 "Directory status"				ifTrue: [^self].
    status = 213 "File status"					ifTrue: [^self].
    status = 214 "Help message"					ifTrue: [^self].
    status = 215 "NAME system type"				ifTrue: [^self].
    status = 220 "Service ready for new user"			ifTrue: [^self].
    status = 221 "Service closing control connection"		ifTrue: [^self].
    status = 225 "Data connection open"				ifTrue: [^self].
    status = 226 "Closing data connection"			ifTrue: [^self].
    status = 227 "Entering Passive Mode"			ifTrue: [^self].
    status = 230 "User logged in"				ifTrue: [^self].
    status = 250 "Requested file action okay"			ifTrue: [^self].
    status = 257 "'PATHNAME' created"				ifTrue: [^self].

    "Positive Intermediate reply"
    status = 331 "User name okay"				ifTrue: [^self].
    status = 332 "Need account for login"			ifTrue: [^self].
    status = 350 "Requested file action pending"		ifTrue: [^self].

    "Transient Negative Completion reply"
    status = 421 "Service not available"			ifTrue: [^errorBlock value].
    status = 425 "Can't open data connection"			ifTrue: [^errorBlock value].
    status = 426 "Connection closed"				ifTrue: [^errorBlock value].
    status = 450 "Requested file action not taken"		ifTrue: [^errorBlock value].
    status = 451 "Requested action aborted"			ifTrue: [^errorBlock value].
    status = 452 "Requested action not taken"			ifTrue: [^errorBlock value].

    "Permanent Negative Completion reply"
    status = 500 "Syntax error"					ifTrue: [^errorBlock value].
    status = 501 "Syntax error"					ifTrue: [^errorBlock value].
    status = 502 "Command not implemented"			ifTrue: [^errorBlock value].
    status = 503 "Bad sequence of commands"			ifTrue: [^errorBlock value].
    status = 504 "Command not implemented"			ifTrue: [^errorBlock value].
    status = 530 "Not logged in"				ifTrue: [^self loginIncorrectError: response statusMessage].
    status = 532 "Need account for storing files"		ifTrue: [^errorBlock value].
    status = 550 "Requested action not taken"			ifTrue: [^self fileNotFoundError: response statusMessage].
    status = 551 "Requested action aborted"			ifTrue: [^errorBlock value].
    status = 552 "Requested file action aborted"		ifTrue: [^errorBlock value].
    status = 553 "Requested action not taken"			ifTrue: [^errorBlock value].

    "Unknown status"
    ^errorBlock value!

fileNotFoundError: errorString
    ^FTPFileNotFoundError signal: errorString! !


Namespace current: Smalltalk!