yahns Ruby server user/dev discussion
 help / color / mirror / code / Atom feed
blob 8f4790e32a5cbc7faccc58fe93d7d1ec53e4ab82 8074 bytes (raw)
name: lib/yahns/proxy_http_response.rb 	 # note: path name is non-authoritative(*)

  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
 
# -*- encoding: binary -*-
# Copyright (C) 2015 all contributors <yahns-public@yhbt.net>
# License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt)

# loaded by yahns/proxy_pass, this relies on Yahns::HttpResponse for
# constants.
module Yahns::HttpResponse # :nodoc:

  # write everything in buf to our client socket (or wbuf, if it exists)
  # it may return a newly-created wbuf or nil
  def proxy_write(wbuf, buf, alive)
    unless wbuf
      # no write buffer, try to write directly to the client socket
      case rv = String === buf ? kgio_trywrite(buf) : kgio_trywritev(buf)
      when nil then return # done writing buf, likely
      when String, Array # partial write, hope the skb grows
        buf = rv
      when :wait_writable, :wait_readable
        wbuf = Yahns::Wbuf.new(nil, alive, self.class.output_buffer_tmpdir, rv)
        buf = buf.join if Array === buf
        break
      end while true
    end

    wbuf.wbuf_write(self, buf)
    wbuf.busy ? wbuf : nil
  end

  def proxy_err_response(code, req_res, exc, wbuf)
    logger = @hs.env['rack.logger']
    case exc
    when nil
      logger.error('premature upstream EOF')
    when Kcar::ParserError
      logger.error("upstream response error: #{exc.message}")
    else
      Yahns::Log.exception(logger, 'upstream error', exc)
    end
    # try to write something, but don't care if we fail
    Integer === code and
      kgio_trywrite("HTTP/1.1 #{CODES[code]}\r\n\r\n") rescue nil

    shutdown rescue nil
    req_res.shutdown rescue nil
    nil # signal close of req_res from yahns_step in yahns/proxy_pass.rb
  ensure
    wbuf.wbuf_abort if wbuf
  end

  # returns :wait_readable if we need to read more from req_res
  # returns :ignore if we yield control to the client(self)
  # returns nil if completely done
  def proxy_response_start(res, tip, kcar, req_res)
    status, headers = res
    si = status.to_i
    status = CODES[si] || status
    env = @hs.env
    have_body = !Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include?(si) &&
                env[REQUEST_METHOD] != HEAD
    flags = MSG_DONTWAIT
    rechunk = false
    k = self.class
    alive = @hs.next? && k.persistent_connections

    res = "HTTP/1.1 #{status}\r\n"
    headers.each do |key,value| # n.b.: headers is an Array of 2-element Arrays
      case key
      when /\A(?:Connection|Keep-Alive)\z/i
        next # do not let some upstream headers leak through
      when %r{\AContent-Length\z}i
        flags |= MSG_MORE if have_body && value.to_i > 0
      when %r{\ATransfer-Encoding\z}i
        if value =~ /\bchunked\b/i
          case env['HTTP_VERSION'] # this is the original client request
          when 'HTTP/1.1'
            rechunk = true
          else
            # too expensive to calculate Content-Length for HTTP/1.0
            # persistent clients, so we will drop persistence instead
            alive = false # this should already be implied
            next
          end
        end
      end

      res << "#{key}: #{value}\r\n"
    end

    # For now, do not add a Date: header, assume upstream already did it
    # but do not care if they did not
    res << (alive ? CONN_KA : CONN_CLOSE)

    # send the headers
    case rv = kgio_syssend(res, flags)
    when nil then break # all done, likely
    when String # partial write, highly unlikely
      flags = MSG_DONTWAIT
      res = rv # hope the skb grows
    when :wait_writable, :wait_readable # highly unlikely in real apps
      wbuf = proxy_write(nil, res, alive)
      break # keep buffering as much as possible
    end while true

    rbuf = Thread.current[:yahns_rbuf]
    tip = tip.empty? ? [] : [ tip ]

    if have_body
      if len = kcar.body_bytes_left

        case tmp = tip.shift || req_res.kgio_tryread(0x2000, rbuf)
        when String
          len = kcar.body_bytes_left -= tmp.size
          wbuf = proxy_write(wbuf, tmp, alive)
        when nil # premature EOF
          return proxy_err_response(nil, req_res, nil, wbuf)
        when :wait_readable
          # for ensure:
          wbuf ||= Yahns::Wbuf.new(nil, alive, k.output_buffer_tmpdir, false)
          return :wait_readable # self remains in :ignore, wait on upstream
        end until len == 0

      else # nasty chunked body

        # Only HTTP/1.1 supports chunked responses, we must translate
        # otherwise.  Otherwise, we must drop the connection to signal
        # the end.  We only send HTTP/1.1 requests to the upstream so
        # Rack/Rails can always send streaming responses.
        buf = ''
        case tmp = tip.shift || req_res.kgio_tryread(0x2000, rbuf)
        when String
          kcar.filter_body(buf, tmp)
          unless buf.empty?
            tmp = rechunk ? [ "#{buf.size.to_s(16)}\r\n", buf, "\r\n".freeze ]
                          : buf
            wbuf = proxy_write(wbuf, tmp, alive)
          end
        when nil # premature EOF
          return proxy_err_response(nil, req_res, nil, wbuf)
        when :wait_readable
          # for ensure:
          wbuf ||= Yahns::Wbuf.new(nil, alive, k.output_buffer_tmpdir, false)
          return :wait_readable # self remains in :ignore, wait on upstream
        end until kcar.body_eof?

        # TODO: Trailer support
        wbuf = proxy_write(wbuf, "0\r\n\r\n".freeze, alive) if rechunk
      end
    end

    wbuf and return proxy_busy_mod_blocked(wbuf, wbuf.busy)
    proxy_busy_mod_done(alive)
  rescue => e
    proxy_err_response(502, req_res, e, wbuf)
  ensure
    # this happens if this method returns :wait_readable
    req_res.resbuf = wbuf if wbuf
  end

  def proxy_response_finish(kcar, wbuf, req_res)
    rbuf = Thread.current[:yahns_rbuf]
    if len = kcar.body_bytes_left

      case tmp = req_res.kgio_tryread(0x2000, rbuf)
      when String
        len = kcar.body_bytes_left -= tmp.size
        wbuf.wbuf_write(self, tmp)
      when nil # premature EOF
        return proxy_err_response(nil, req_res, nil, wbuf)
      when :wait_readable
        return :wait_readable # self remains in :ignore, wait on upstream
      end while len != 0

    else # nasty chunked body

      # Only HTTP/1.1 supports chunked responses, we must translate
      # otherwise.  Otherwise, we must drop the connection to signal
      # the end.  We only send HTTP/1.1 requests to the upstream so
      # Rack/Rails can always send streaming responses.
      rechunk = @hs.env['HTTP_VERSION'] == 'HTTP/1.1'.freeze
      buf = ''
      case tmp = req_res.kgio_tryread(0x2000, rbuf)
      when String
        kcar.filter_body(buf, tmp)
        unless buf.empty?
          tmp = rechunk ? [ "#{buf.size.to_s(16)}\r\n", buf, "\r\n".freeze ]
                        : buf
          wbuf.wbuf_write(self, tmp)
        end
      when nil # premature EOF
        return proxy_err_response(nil, req_res, nil, wbuf)
      when :wait_readable
        return :wait_readable # self remains in :ignore, wait on upstream
      end until kcar.body_eof?

      # TODO: Trailer support
      wbuf.wbuf_write(self, "0\r\n\r\n".freeze) if rechunk
    end

    busy = wbuf.busy and return proxy_busy_mod_blocked(wbuf, busy)
    proxy_busy_mod_done(wbuf.wbuf_persist)
  end

  def proxy_busy_mod_done(alive)
    q = Thread.current[:yahns_queue]
    case http_response_done(alive)
    when :wait_readable then q.queue_mod(self, Yahns::Queue::QEV_RD)
    when :wait_writable then q.queue_mod(self, Yahns::Queue::QEV_WR)
    when :close then Thread.current[:yahns_fdmap].sync_close(self)
    end

    nil # close the req_res, too
  end

  def proxy_busy_mod_blocked(wbuf, busy)
    q = Thread.current[:yahns_queue]
    # we are completely done reading and buffering the upstream response,
    # but have not completely written the response to the client,
    # yield control to the client socket:
    @state = wbuf
    case busy
    when :wait_readable then q.queue_mod(self, Yahns::Queue::QEV_RD)
    when :wait_writable then q.queue_mod(self, Yahns::Queue::QEV_WR)
    else
      abort "BUG: invalid wbuf.busy: #{busy.inspect}"
    end
    # no touching self after queue_mod
    :ignore
  end
end

debug log:

solving 8f4790e ...
found 8f4790e in https://yhbt.net/yahns.git/

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://yhbt.net/yahns.git/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).