2 LuCI - Lua Development Framework
4 Copyright 2009 Steven Barth <steven@midlink.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
16 local nixio = require "nixio"
17 local httpclient = require "luci.httpclient"
18 local ltn12 = require "luci.ltn12"
22 module "luci.httpclient.receiver"
24 local function prepare_fd(target)
25 -- Open fd for appending
26 local file, code, msg = nixio.open(target, "r+")
27 if not file and code == nixio.const.ENOENT then
28 file, code, msg = nixio.open(target, "w")
34 return file, code, msg
38 local stat, code, msg = file:lock("ex", "nb")
40 return stat, code, msg
49 function request_to_file(uri, target, options, cbs)
50 options = options or {}
52 options.headers = options.headers or {}
53 local hdr = options.headers
55 local file, code, msg = prepare_fd(target)
57 return file, code, msg
60 local off = file:tell()
64 hdr.Range = hdr.Range or ("bytes=" .. off .. "-")
67 local code, resp, buffer, sock = httpclient.request_raw(uri, options)
71 return code, resp, buffer
72 elseif hdr.Range and code ~= 206 then
73 -- We wanted a part but we got the while file
76 return nil, -4, code, resp
77 elseif not hdr.Range and code ~= 200 then
78 -- We encountered an error
81 return nil, -4, code, resp
85 cbs.on_header(file, code, resp)
88 local chunked = resp.headers["Transfer-Encoding"] == "chunked"
90 -- Write the buffer to file
92 print ("Buffered data: " .. #buffer .. " Byte")
95 if not sock:is_socket() or chunked then
99 -- This is a plain TCP socket and there is no encoding so we can splice
101 local pipein, pipeout, msg = nixio.pipe()
105 return pipein, pipeout, msg
109 -- Disable blocking for the pipe otherwise we might end in a deadlock
110 local stat, code, msg = pipein:setblocking(false)
112 stat, code, msg = pipeout:setblocking(false)
117 return stat, code, msg
121 -- Adjust splice values
123 local smode = nixio.splice_flags("move", "more", "nonblock")
125 local stat, code, msg = nixio.splice(sock, pipeout, ssize, smode)
131 {fd=sock, events=nixio.poll_flags("in")}
135 {fd=file, events=nixio.poll_flags("out")}
143 nixio.poll(pollsock, 15000)
145 stat, code, msg = nixio.splice(sock, pipeout, ssize, smode)
149 return stat, code, msg
150 elseif stat == 0 then
158 nixio.poll(pollfile, 15000)
160 stat, code, msg = nixio.splice(pipein, file, ssize, smode)
164 return stat, code, msg
178 print "Warning: splice() failed, falling back to read/write mode"
180 local src = chunked and httpclient.chunksource(sock) or sock:blocksource()
181 local snk = file:sink()
184 src = ltn12.source.chain(src, function(chunk)
190 -- Fallback to read/write
191 local stat, code, msg = ltn12.pump.all(src, snk)
196 return stat, code, msg