-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCMD_wget.lua
94 lines (90 loc) · 2.11 KB
/
CMD_wget.lua
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
local cmds_wget={}
local function putcontents(filename,data)
local fd = file.open(filename, "w")
if fd == nil then return nil end
if (fd:write(data) == nil) then return nil end
fd:close()
return true
end
function cmds_wget.wget(ctx,url,filename,md5,async)
local ret=0
local count=0
local hash
local fd
if (filename == nil) then
filename=url:gsub(".*/", "")
end
if (filename == 'ota:') then
otaupgrade.commence()
else
fd=shell.open(ctx,"wget.tmp", "w")
if (fd == nil) then
return -1
end
end
if (md5 ~= nil) then
hash=crypto.new_hash("MD5")
end
ctx.stdout:write("Getting '"..url.."' to '"..filename.."' ")
connection = http.createConnection(url, http.GET, { async=async } )
connection:on("complete", function(status, connected)
if (filename ~= 'ota:') then
fd:close()
end
ctx.stdout:write("\nRequest completed with status code "..status..','..count.." packets\n")
if (status == 200) then
if (hash) then
digest=hash:finalize()
hex=''
for i=1,digest:len() do
hex=hex..string.format('%02x',string.byte(digest,i))
end
if (hex ~= md5) then
ctx.stderr:write("MD5 failed "..hex.." vs " .. md5 .. "\n")
ret=-1
return ret
end
end
if (filename == 'ota:') then
otaupgrade.complete()
ctx.stdout:write("Update complete, please reboot\n")
else
file.remove(filename)
if (file.rename("wget.tmp",filename) == nil) then
ctx.stderr:print("failed to rename file")
ret=-1
end
end
end
end)
connection:on("data", function(status, data)
ctx.stdout:write(".")
if (tmr.wdclr) then
tmr.wdclr()
end
if (hash) then
hash:update(data)
end
count=count+1
if (filename == 'ota:') then
otaupgrade.write(data)
else
if (fd:write(data) == nil) then
ctx.stderr:print("failed to write wget.tmp")
ret=-1
connection:close()
end
end
if ((count % 100) == 0 and async) then
t=tmr.create()
t:alarm(10, tmr.ALARM_SINGLE, function() connection:ack() end)
return http.DELAYACK
end
end)
connection:request()
if (async) then
ctx.stdout:write("Resuming in Background\n")
end
return ret
end
return cmds_wget