aboutsummaryrefslogblamecommitdiffstats
path: root/actionmailer/lib/action_mailer/vendor/tmail/encode.rb
blob: 8f33386f4d91c94acb33ca460b45a9980cc1b40c (plain) (tree)
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






























































































































































































































































































































































































































































                                                                           
#
# encode.rb
#
# Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#

require 'nkf'
require 'tmail/base64.rb'
require 'tmail/stringio'
require 'tmail/utils'


module TMail

  module StrategyInterface

    def create_dest( obj )
      case obj
      when nil
        StringOutput.new
      when String
        StringOutput.new(obj)
      when IO, StringOutput
        obj
      else
        raise TypeError, 'cannot handle this type of object for dest'
      end
    end
    module_function :create_dest

    def encoded( eol = "\r\n", charset = 'j', dest = nil )
      accept_strategy Encoder, eol, charset, dest
    end

    def decoded( eol = "\n", charset = 'e', dest = nil )
      accept_strategy Decoder, eol, charset, dest
    end

    alias to_s decoded
  
    def accept_strategy( klass, eol, charset, dest = nil )
      dest ||= ''
      accept klass.new(create_dest(dest), charset, eol)
      dest
    end

  end


  ###
  ### MIME B encoding decoder
  ###

  class Decoder

    include TextUtils

    encoded = '=\?(?:iso-2022-jp|euc-jp|shift_jis)\?[QB]\?[a-z0-9+/=]+\?='
    ENCODED_WORDS = /#{encoded}(?:\s+#{encoded})*/i

    OUTPUT_ENCODING = {
      'EUC'  => 'e',
      'SJIS' => 's',
    }

    def self.decode( str, encoding = nil )
      encoding ||= (OUTPUT_ENCODING[$KCODE] || 'j')
      opt = '-m' + encoding
      str.gsub(ENCODED_WORDS) {|s| NKF.nkf(opt, s) }
    end

    def initialize( dest, encoding = nil, eol = "\n" )
      @f = StrategyInterface.create_dest(dest)
      @encoding = (/\A[ejs]/ === encoding) ? encoding[0,1] : nil
      @eol = eol
    end

    def decode( str )
      self.class.decode(str, @encoding)
    end
    private :decode

    def terminate
    end

    def header_line( str )
      @f << decode(str)
    end

    def header_name( nm )
      @f << nm << ': '
    end

    def header_body( str )
      @f << decode(str)
    end
      
    def space
      @f << ' '
    end

    alias spc space

    def lwsp( str )
      @f << str
    end
      
    def meta( str )
      @f << str
    end

    def text( str )
      @f << decode(str)
    end

    def phrase( str )
      @f << quote_phrase(decode(str))
    end

    def kv_pair( k, v )
      @f << k << '=' << v
    end

    def puts( str = nil )
      @f << str if str
      @f << @eol
    end

    def write( str )
      @f << str
    end

  end


  ###
  ### MIME B-encoding encoder
  ###

  #
  # FIXME: This class can handle only (euc-jp/shift_jis -> iso-2022-jp).
  #
  class Encoder

    include TextUtils

    BENCODE_DEBUG = false unless defined?(BENCODE_DEBUG)

    def Encoder.encode( str )
      e = new()
      e.header_body str
      e.terminate
      e.dest.string
    end

    SPACER       = "\t"
    MAX_LINE_LEN = 70

    OPTIONS = {
      'EUC'  => '-Ej -m0',
      'SJIS' => '-Sj -m0',
      'UTF8' => nil,      # FIXME
      'NONE' => nil
    }

    def initialize( dest = nil, encoding = nil, eol = "\r\n", limit = nil )
      @f = StrategyInterface.create_dest(dest)
      @opt = OPTIONS[$KCODE]
      @eol = eol
      reset
    end

    def normalize_encoding( str )
      if @opt
      then NKF.nkf(@opt, str)
      else str
      end
    end

    def reset
      @text = ''
      @lwsp = ''
      @curlen = 0
    end

    def terminate
      add_lwsp ''
      reset
    end

    def dest
      @f
    end

    def puts( str = nil )
      @f << str if str
      @f << @eol
    end

    def write( str )
      @f << str
    end

    #
    # add
    #

    def header_line( line )
      scanadd line
    end

    def header_name( name )
      add_text name.split(/-/).map {|i| i.capitalize }.join('-')
      add_text ':'
      add_lwsp ' '
    end

    def header_body( str )
      scanadd normalize_encoding(str)
    end

    def space
      add_lwsp ' '
    end

    alias spc space

    def lwsp( str )
      add_lwsp str.sub(/[\r\n]+[^\r\n]*\z/, '')
    end

    def meta( str )
      add_text str
    end

    def text( str )
      scanadd normalize_encoding(str)
    end

    def phrase( str )
      str = normalize_encoding(str)
      if CONTROL_CHAR === str
        scanadd str
      else
        add_text quote_phrase(str)
      end
    end

    # FIXME: implement line folding
    #
    def kv_pair( k, v )
      v = normalize_encoding(v)
      if token_safe?(v)
        add_text k + '=' + v
      elsif not CONTROL_CHAR === v
        add_text k + '=' + quote_token(v)
      else
        # apply RFC2231 encoding
        kv = k + '*=' + "iso-2022-jp'ja'" + encode_value(v)
        add_text kv
      end
    end

    def encode_value( str )
      str.gsub(TOKEN_UNSAFE) {|s| '%%%02x' % s[0] }
    end

    private

    def scanadd( str, force = false )
      types = ''
      strs = []

      until str.empty?
        if m = /\A[^\e\t\r\n ]+/.match(str)
          types << (force ? 'j' : 'a')
          strs.push m[0]

        elsif m = /\A[\t\r\n ]+/.match(str)
          types << 's'
          strs.push m[0]

        elsif m = /\A\e../.match(str)
          esc = m[0]
          str = m.post_match
          if esc != "\e(B" and m = /\A[^\e]+/.match(str)
            types << 'j'
            strs.push m[0]
          end

        else
          raise 'TMail FATAL: encoder scan fail'
        end
        str = m.post_match
      end

      do_encode types, strs
    end

    def do_encode( types, strs )
      #
      # result  : (A|E)(S(A|E))*
      # E       : W(SW)*
      # W       : (J|A)+ but must contain J  # (J|A)*J(J|A)*
      # A       : <<A character string not to be encoded>>
      # J       : <<A character string to be encoded>>
      # S       : <<LWSP>>
      #
      # An encoding unit is `E'.
      # Input (parameter `types') is  (J|A)(J|A|S)*(J|A)
      #
      if BENCODE_DEBUG
        puts
        puts '-- do_encode ------------'
        puts types.split(//).join(' ')
        p strs
      end

      e = /[ja]*j[ja]*(?:s[ja]*j[ja]*)*/

      while m = e.match(types)
        pre = m.pre_match
        concat_A_S pre, strs[0, pre.size] unless pre.empty?
        concat_E m[0], strs[m.begin(0) ... m.end(0)]
        types = m.post_match
        strs.slice! 0, m.end(0)
      end
      concat_A_S types, strs
    end

    def concat_A_S( types, strs )
      i = 0
      types.each_byte do |t|
        case t
        when ?a then add_text strs[i]
        when ?s then add_lwsp strs[i]
        else
          raise "TMail FATAL: unknown flag: #{t.chr}"
        end
        i += 1
      end
    end
    
    METHOD_ID = {
      ?j => :extract_J,
      ?e => :extract_E,
      ?a => :extract_A,
      ?s => :extract_S
    }

    def concat_E( types, strs )
      if BENCODE_DEBUG
        puts '---- concat_E'
        puts "types=#{types.split(//).join(' ')}"
        puts "strs =#{strs.inspect}"
      end

      flush() unless @text.empty?

      chunk = ''
      strs.each_with_index do |s,i|
        mid = METHOD_ID[types[i]]
        until s.empty?
          unless c = __send__(mid, chunk.size, s)
            add_with_encode chunk unless chunk.empty?
            flush
            chunk = ''
            fold
            c = __send__(mid, 0, s)
            raise 'TMail FATAL: extract fail' unless c
          end
          chunk << c
        end
      end
      add_with_encode chunk unless chunk.empty?
    end

    def extract_J( chunksize, str )
      size = max_bytes(chunksize, str.size) - 6
      size = (size % 2 == 0) ? (size) : (size - 1)
      return nil if size <= 0
      "\e$B#{str.slice!(0, size)}\e(B"
    end

    def extract_A( chunksize, str )
      size = max_bytes(chunksize, str.size)
      return nil if size <= 0
      str.slice!(0, size)
    end

    alias extract_S extract_A

    def max_bytes( chunksize, ssize )
      (restsize() - '=?iso-2022-jp?B??='.size) / 4 * 3 - chunksize
    end

    #
    # free length buffer
    #

    def add_text( str )
      @text << str
      # puts '---- text -------------------------------------'
      # puts "+ #{str.inspect}"
      # puts "txt >>>#{@text.inspect}<<<"
    end

    def add_with_encode( str )
      @text << "=?iso-2022-jp?B?#{Base64.encode(str)}?="
    end

    def add_lwsp( lwsp )
      # puts '---- lwsp -------------------------------------'
      # puts "+ #{lwsp.inspect}"
      fold if restsize() <= 0
      flush
      @lwsp = lwsp
    end

    def flush
      # puts '---- flush ----'
      # puts "spc >>>#{@lwsp.inspect}<<<"
      # puts "txt >>>#{@text.inspect}<<<"
      @f << @lwsp << @text
      @curlen += (@lwsp.size + @text.size)
      @text = ''
      @lwsp = ''
    end

    def fold
      # puts '---- fold ----'
      @f << @eol
      @curlen = 0
      @lwsp = SPACER
    end

    def restsize
      MAX_LINE_LEN - (@curlen + @lwsp.size + @text.size)
    end

  end

end    # module TMail