summaryrefslogtreecommitdiff
path: root/lib/net/session.rb
blob: 3f7ef7f51fd00cdc0146eaf4f3d0f2cdacd699db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
=begin

= Net module version 1.0.2 reference manual

session.rb written by Minero Aoki <aamine@dp.u-netsurf.ne.jp>

This library is distributed under the terms of Ruby style license.
You can freely distribute/modify/copy this file.

=end


require 'socket'


class String

  def doquote
    str = self.gsub( "\n", '\\n' )
    str.gsub!( "\r", '\\r' )
    str.gsub!( "\t", '\\t' )
    return str
  end

end


=begin

== Net::Session

the abstruct class for Internet session

=== Super Class

Object

=== Constants

: Version

  The version of Session class. It is a string like "1.0.2".

=end


module Net

  class Session

    Version = '1.0.2'

=begin

=== Class Methods

: new( address = 'localhost', port = nil )

  This method Create a new Session object.

: start( address = 'localhost', port = nil, *args )
: start( address = 'localhost', port = nil, *args ){|session| .... }

  This method create a new Session object and start session.
  If you call this method with block, Session object give itself
  to block and finish session when block returns.

=end

    def initialize( addr = 'localhost', port = nil )
      proto_initialize
      @address = addr
      @port    = port if port
      @active  = false
    end

    class << self
      def start( address = 'localhost', port = nil, *args )
        inst = new( address, port )
        ret = inst.start( *args )

        if iterator? then
          ret = yield( inst )
          inst.finish
        end
        return ret
      end
    end

=begin

=== Methods

: address

  the address of connecting server (FQDN).

: port

  connecting port number

=end

    attr :address
    attr :port

    attr :socket

    attr :proto_type
    attr :proto, true

=begin

: start( *args )

  This method start session. If you call this method when the session
  is already started, this only returns false without doing anything.

  '*args' are specified in subclasses.

: finish

  This method finish session. If you call this method before session starts,
  it only return false without doing anything.

: active?

  true if session have been started

=end

    def start( *args )
      return false if active?
      @active = true

      if ProtocolSocket === args[0] then
        @socket = args.shift
        @socket.pipe = @pipe
      else
        @socket = ProtocolSocket.open( @address, @port, @pipe )
      end
      @pipe = nil

      @proto = @proto_type.new( @socket )
      do_start( *args )
    end

    def finish
      @active = false

      if @proto then
        do_finish
        @proto = nil

        return true
      else
        return false
      end
    end

    def active?() @active end

    def set_pipe( arg )
      @pipe = arg
    end

  end


=begin

== Net::Command

=== Super Class

Object

=== Class Methods

: new( socket )

  This method create new Command object. 'socket' must be ProtocolSocket.
  This method is abstract class.


=== Methods

: quit

  This method finishes protocol.

=end

  class Command

    def initialize( sock )
      @socket = sock
      check_reply( SuccessCode )
    end

    attr :socket, true

    def quit
      if @socket and not @socket.closed? then
        begin
          do_quit
        ensure
          @socket.close unless @socket.closed?
          @socket = nil
        end
      end
    end

    private

    def check_reply( *oks )
      rep = get_reply
      oks.each do |i|
        if i === rep then
          return rep
        end
      end

      rep.error! @socket.sending
    end
    
  end


  class ProtocolError        < StandardError   ; end
  class   ProtoSyntaxError   <   ProtocolError ; end
  class   ProtoFatalError    <   ProtocolError ; end
  class   ProtoUnknownError  <   ProtocolError ; end
  class   ProtoServerError   <   ProtocolError ; end
  class   ProtoAuthError     <   ProtocolError ; end
  class   ProtoCommandError  <   ProtocolError ; end

  class ReplyCode

    def initialize( cod, mes )
      @code = cod
      @msg  = mes
    end

    attr :code
    attr :msg

    def error!( sending )
      err, tag = Errors[ self.type ]
      mes = sprintf( <<MES, tag, @code, sending.doquote, @msg.doquote )

%s: status %s
writing string is:
%s

error message from server is:
%s
MES
      raise err, mes
    end

  end

  class SuccessCode     < ReplyCode ; end
  class ContinueCode    < SuccessCode ; end
  class ErrorCode       < ReplyCode ; end
  class SyntaxErrorCode < ErrorCode ; end
  class FatalErrorCode  < ErrorCode ; end
  class ServerBusyCode  < ErrorCode ; end
  class UnknownCode     < ReplyCode ; end

  class ReplyCode
    Errors = {
      SuccessCode     => [ ProtoUnknownError, 'unknown error' ],
      ContinueCode    => [ ProtoUnknownError, 'unknown error' ],
      ErrorCode       => [ ProtocolError, 'protocol error' ],
      SyntaxErrorCode => [ ProtoSyntaxError, 'syntax error' ],
      FatalErrorCode  => [ ProtoFatalError, 'fatal error' ],
      ServerBusyCode  => [ ProtoServerError, 'probably server busy' ],
      UnknownCode     => [ ProtoUnknownError, 'unknown error' ]
    }
  end


=begin

== Net::ProtocolSocket

=== Super Class

Object

=== Class Methods

: new( address = 'localhost', port = nil )

  This create new ProtocolSocket object, and connect to server.

=end

  class ProtocolSocket

    def initialize( addr, port, pipe = nil )
      @address = addr
      @port    = port
      @pipe    = pipe

      @ipaddr  = ''
      @closed  = false
      @sending = ''
      @buffer  = ''

      @socket = TCPsocket.new( addr, port )
      @ipaddr = @socket.addr[3]
    end

    attr :pipe, true

    class << self
      alias open new
    end

=begin

=== Methods

: close

  This method closes socket.

: addr

  a FQDN address of server

: ipaddr

  an IP address of server

: port

  connecting port number.

: closed?

  true if ProtocolSokcet have been closed already

=end

    attr :socket, true

    def close
      @socket.close
      @closed = true
    end

    def closed?() @closed end

    def addr() @address.dup end
    def port() @port end
    def ipaddr() @ipaddr.dup end

    attr :sending


    CRLF    = "\r\n"
    D_CRLF  = ".\r\n"
    TERMEXP = /\n|\r\n|\r/o


=begin

: read( length )

  This method read 'length' bytes and return the string.

: readuntil( target )

  This method read until find 'target'. Returns read string.

: readline

  read until "\r\n" and returns it without "\r\n".

: read_pendstr

  This method read until "\r\n.\r\n".
  At the same time, delete period at line head and final line ("\r\n.\r\n").

: read_pendlist
: read_pendlist{|line| .... }

  This method read until "\r\n.\r\n". This method resembles to 'read_pendstr',
  but 'read_pendlist' don't check period at line head, and returns array which
  each element is one line.

  When this method was called with block, evaluate it for each reading a line.

=end

    def read( len, ret = '' )
      rsize = 0

      while rsize + @buffer.size < len do
        rsize += @buffer.size
        ret << fetch_rbuf( @buffer.size )
        fill_rbuf
      end
      ret << fetch_rbuf( len - rsize )

      return ret
    end


    def readuntil( target )
      until idx = @buffer.index( target ) do
        fill_rbuf
      end

      return fetch_rbuf( idx + target.size )
    end

        
    def readline
      ret = readuntil( CRLF )
      ret.chop!
      return ret
    end


    def read_pendstr( dest = '' )
      @pipe << "reading text...\n" if pre = @pipe ; @pipe = nil

      rsize = 0

      while (str = readuntil( CRLF )) != D_CRLF do
        rsize += str.size
        str.gsub!( /\A\./o, '' )
        dest << str
      end

      @pipe << "read #{rsize} bytes\n" if @pipe = pre
      return dest
    end


    def read_pendlist
      @pipe << "reading list...\n" if pre = @pipe ; @pipe = nil

      arr = []
      str = nil
      call = iterator?

      while (str = readuntil( CRLF )) != D_CRLF do
        str.chop!
        arr.push str
        yield str if iterator?
      end

      @pipe << "read #{arr.size} lines\n" if @pipe = pre
      return arr
    end


    private


    READ_BLOCK = 1024 * 8

    def fill_rbuf
      @buffer << @socket.sysread( READ_BLOCK )
    end

    def fetch_rbuf( len )
      bsi = @buffer.size
      ret = @buffer[ 0, len ]
      @buffer = @buffer[ len, bsi - len ]

      @pipe << %{read  "#{debugstr ret}"\n} if @pipe
      return ret
    end


=begin

: write( src )

  This method send 'src'. ProtocolSocket read strings from 'src' by 'each'
  iterator. This method returns written bytes.

: writebin( src )

  This method send 'src'. ProtocolSokcet read string from 'src' by 'each'
  iterator. This method returns written bytes.

: writeline( str )

  This method writes 'str'. There has not to be bare "\r" or "\n" in 'str'.

: write_pendstr( src )

  This method writes 'src' as a mail.
  ProtocolSocket reads strings from 'src' by 'each' iterator.
  This returns written bytes.

=end

    public


    def write( src )
      do_write_beg
      each_crlf_line( src ) do |line|
        do_write_do line
      end
      return do_write_fin
    end


    def writebin( src )
      do_write_beg
      src.each do |bin|
        do_write_do bin
      end
      return do_write_fin
    end


    def writeline( str )
      do_write_beg
      do_write_do str
      do_write_do CRLF
      return do_write_fin
    end


    def write_pendstr( src )
      @pipe << "writing text from #{src.type}" if pre = @pipe ; @pipe = nil

      do_write_beg
      each_crlf_line( src ) do |line|
        do_write_do '.' if line[0] == ?.
        do_write_do line
      end
      do_write_do D_CRLF
      wsize = do_write_fin

      @pipe << "wrote #{wsize} bytes text" if @pipe = pre
      return wsize
    end


    private


    def each_crlf_line( src )
      buf = ''
      beg = 0
      pos = nil

      src.each do |b|
        buf << b

        beg = 0
        while (pos = buf.index(TERMEXP, beg)) and (pos < buf.size - 2) do
          pos += $&.size
          tmp = buf[ beg, pos - beg ]
          tmp.chop!
          yield tmp << CRLF
          beg = pos
        end
        buf = buf[ beg, buf.size - beg ] if beg != 0
      end

      buf << "\n" unless /\n|\r/o === buf[-1,1]

      beg = 0
      while pos = buf.index( TERMEXP, beg ) do
        pos += $&.size
        tmp = buf[ beg, pos - beg ]
        tmp.chop!
        yield tmp << CRLF
        beg = pos
      end
    end


    def do_write_beg
      @wtmp = 'write "' if @pipe

      @writtensize = 0
      @sending = ''
    end

    def do_write_do( arg )
      @wtmp << debugstr( arg ) if @pipe

      if @sending.size < 128 then
        @sending << arg
      else
        @sending << '...' unless @sending[-1] == ?.
      end

      s = @socket.write( arg )
      @writtensize += s
      return s
    end

    def do_write_fin
      if @pipe then
        @wtmp << "\n"
        @pipe << @wtmp
        @wtmp = nil
      end

      @socket.flush
      return @writtensize
    end


    def debugstr( str )
      ret = ''
      while str and tmp = str[ 0, 50 ] do
        str = str[ 50, str.size - 50 ]
        tmp = tmp.inspect
        ret << tmp[ 1, tmp.size - 2 ]
      end
      ret
    end

  end

end