Module: Watobo::Mixins::RequestParser

Defined in:
lib/watobo/mixins/request_parser.rb

Overview

This mixin can be used to parse a String or any object which supports method.to_s into a valid http request string

Instance Method Summary collapse

Instance Method Details

#parse_code(prefs = {}) ⇒ Object

This method parses (eval) ruby code which is included in the string. Ruby code is identified by its surrounding delimiters - default: ‘%%’. For examples the string ‘ABC%%“_”*10%%DEFG’ will result to ‘ABC__________DEFG’

Possible prefs:

:code_dlmtr [String] - set ruby code delimiter



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
# File 'lib/watobo/mixins/request_parser.rb', line 14

def parse_code(prefs={})
  cprefs = { :code_dlmtr => '%%' } # default delimiter for ruby code
  cprefs.update(prefs)

  #pattern="(#{cprefs[:code_dlmtr]}.*?#{cprefs[:code_dlmtr]})"
  pattern = cprefs[:code_dlmtr]
  request = self.to_s
  expression = ""

  begin
    # puts new_request
    expr = ''

    pos = 0
    off = 0
    match = []
    code_marks = []
    while pos >= 0 and pos < request.length
      code_offset = request.index(pattern, pos)

      unless code_offset.nil?
        new_line_index = request.index("\n", pos)   
        unless new_line_index.nil?
          if new_line_index < code_offset
            # new_request << request[match[0]..code_offset-1] unless match.empty?
            match = [] 
            # pos = code_offset
          end
        end
        match << code_offset

        if match.length == 2
          code_marks << match.dup
          match = []
        end
        pos = code_offset + pattern.length
      else
        break
      end
    end

    new_request = ''
    unless code_marks.empty?           
      code_marks.each_with_index do |cm,i|
        #puts cm.to_yaml
        last = i > 0 ? ( code_marks[i-1][1] + pattern.length ) : 0
        new_request << request[last..cm[0]-1] if cm[0] > 0
        exp_start = cm[0] + pattern.length
        exp_end = cm[1] - 1

        expression = request[exp_start..exp_end]
        expression.strip!
        next if expression.empty?
        puts "DEBUG: executing: #{expression}" if $DEBUG
        #result = expression.empty? ? "" : eval("#{expression}")
        result = eval(expression)
        puts "DEBUG: got #{result.class}" if $DEBUG
        if result.is_a? File
          data = result.read
          result.close
        elsif result.is_a? String
          data = result
        elsif result.is_a? Array
          data = result.join
        else
          puts "!!!WATOBO - expression must return String or File !!!"
        end
        new_request << data
      end
      new_request << request[code_marks.last[1]+pattern.length..-1] unless code_marks.last[1] >= request.length-1

    else
      new_request = request
    end

    return new_request

  rescue SyntaxError, LocalJumpError, NameError => e
    #  raise SyntaxError, "SyntaxError in '#{expression}'"
    puts e
    puts e.backtrace

  end
  return nil
end

#to_request(opts = {}) ⇒ Object



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
# File 'lib/watobo/mixins/request_parser.rb', line 101

def to_request(opts={})
  options = { :update_content_length => false }
  options.update opts
  body = nil
  begin
    text = parse_code
    request = []

    eoh = nil
    eoh = text.index("\n\n") unless text.nil?

    unless eoh.nil?
      header = text.slice(0, eoh).split("\n").map{|h| "#{h}\r\n"}
      body = text.slice(eoh+2, text.length-1)
    else
      header = text.split(/\n/).map{|h| "#{h}\r\n"}
      body = nil
    end

    request.concat header

    #Watobo::Request.create request
    request = Watobo::Request.new(request)

    ct = request.content_type_ex
    # puts ct
    # last line is without "\r\n" if text has a body
    if ct =~ /multipart/ and body then
      #Content-Type: multipart/form-data; boundary=---------------------------3035221901842
      if ct =~ /boundary=([\-\w]+)/
        boundary = $1.strip
        chunks = body.split(/--#{boundary}[\-]{0,2}/)
        #chunks.pop # remove "--"
        #puts "Multipart request has #{chunks.length} chunks"
        new_body = []
        chunks.each do |c|
          new_chunk = ''
          #c.gsub!(/[\-]+$/,'')
          next if c.nil?
          next if c.strip.empty?
          c.strip!
          if c =~ /\n\n/
            ctmp = c.split(/\n\n/)
            cheader = ctmp.shift.split(/\n/)
            cbody = ctmp.join("\n\n")
          else
            cheader = c.split(/\n/)
            cbody = nil
          end
          new_chunk = cheader.join("\r\n")
          new_chunk +=  "\r\n\r\n"
          new_chunk += cbody.strip + "\r\n" if cbody

          # puts cbody
          new_body.push new_chunk

        end
        body = "--#{boundary}\r\n"
        body << new_body.join("--#{boundary}\r\n")
        body << "--#{boundary}--\r\n"
      end
      #  body.gsub!(/\n/, "\r\n") if body

    end

    unless body.nil?
      request.push "\r\n"
      request.push body.strip
    end

    request.fixupContentLength() if options[:update_content_length] == true
    return request
  rescue => bang
    puts bang
    puts bang.backtrace
    raise bang
  end
  #return nil
end

#to_request_UNUSED(opts = {}) ⇒ Object



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
# File 'lib/watobo/mixins/request_parser.rb', line 223

def to_request_UNUSED(opts={})
  options = { :update_content_length => false }
  options.update opts
  begin
    text = parse_code
    result = []

    if text =~ /\n\n/
      dummy = text.split(/\n\n/)
      header = dummy.shift.split(/\n/)
      body = dummy.join("\n\n")
    else
      header = text.split(/\n/)
      body = nil
    end

    header.each do |h|
      result.push "#{h}\r\n"
    end

    # result.extend Watobo::Mixin::Parser::Url
    # result.extend Watobo::Mixin::Parser::Web10
    # result.extend Watobo::Mixin::Shaper::Web10
    #Watobo::Request.create result
    result = Watobo::Request.new(result)

    ct = result.content_type
    # last line is without "\r\n" if text has a body
    if ct =~ /multipart\/form/ and body then
      #Content-Type: multipart/form-data; boundary=---------------------------3035221901842
      if ct =~ /boundary=([\-\w]+)/
        boundary = $1.strip
        chunks = body.split(boundary)
        e = chunks.pop # remove "--"
        new_body = []
        chunks.each do |c|
          new_chunk = ''
          c.gsub!(/[\-]+$/,'')
          next if c.nil?
          next if c.strip.empty?
          c.strip!
          if c =~ /\n\n/
            ctmp = c.split(/\n\n/)
            cheader = ctmp.shift.split(/\n/)
            cbody = ctmp.join("\n\n")
          else
            cheader = c.split(/\n/)
            cbody = nil
          end
          new_chunk = cheader.join("\r\n")
          new_chunk +=  "\r\n\r\n"
          new_chunk += cbody.strip + "\r\n" if cbody

          # puts cbody
          new_body.push new_chunk

        end
        body = "--#{boundary}\r\n"
        body += new_body.join("--#{boundary}\r\n")
        body += "--#{boundary}--"
      end
      #  body.gsub!(/\n/, "\r\n") if body

    end

    if body then
      result.push "\r\n"
      result.push body.strip
    end

    result.fixupContentLength() if options[:update_content_length] == true
    return result
  rescue
    raise
  end
  #return nil
end

#to_response(opts = {}) ⇒ Object



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
# File 'lib/watobo/mixins/request_parser.rb', line 181

def to_response(opts={})
  options = { :update_content_length => false }
  options.update opts
  begin
    text = parse_code
    result = []

    if text =~ /\n\n/
      dummy = text.split(/\n\n/)
      header = dummy.shift.split(/\n/)
      body = dummy.join("\n\n")
    else
      header = text.split(/\n/)
      body = nil
    end

    header.each do |h|
      result.push "#{h}\r\n"
    end


    #Watobo::Response.create result
    result = Watobo::Response.new(result)

    if body then
      result.push "\r\n"
      result.push body.strip
    end

    result.fixupContentLength() if options[:update_content_length] == true
    puts ">>"
    puts result
    return result
  rescue => bang
    puts bang
    puts bang.backtrace
    raise bang
  end
  #return nil
end