4 * Copyright (c) 2016 Cisco and/or its affiliates.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 -- LUTE: Lua Unit Test Environment
20 -- AKA what happens when screen tries to marry with lua and expect,
21 -- but escapes mid-ceremony.
23 -- comments: @ayourtch
29 if type(o) == 'table' then
31 for k,v in pairs(o) do
32 if type(k) ~= 'number' then k = '"'..k..'"' end
33 s = s .. '['..k..'] = ' .. vpp.dump(v) .. ','
44 int posix_openpt(int flags);
47 char *ptsname(int fd);
54 typedef long suseconds_t;
60 int open(char *pathname, int flags);
62 int dup2(int oldfd, int newfd);
64 ssize_t read(int fd, void *buf, size_t count);
65 ssize_t write(int fd, const void *buf, size_t count);
68 int fd; /* file descriptor */
69 short events; /* requested events */
70 short revents; /* returned events */
73 int poll(struct pollfd *fds, nfds_t nfds, int timeout);
76 time_t tv_sec; /* seconds */
77 suseconds_t tv_usec; /* microseconds */
80 int gettimeofday(struct timeval *tv, struct timezone *tz);
82 int inet_pton(int af, const char *src, void *dst);
87 void *memset(void *s, int c, size_t n);
88 void *memcpy(void *dest, void *src, size_t n);
89 void *memmove(void *dest, const void *src, size_t n);
90 void *memmem(const void *haystack, size_t haystacklen,
91 const void *needle, size_t needlelen);
100 local tv = ffi.new("struct timeval[1]")
101 local ret = ffi.C.gettimeofday(tv, nil)
102 return tonumber(tv[0].tv_sec) + (tonumber(tv[0].tv_usec)/1000000.0)
106 local when_wakeup = os_time() + n
107 while os_time() <= when_wakeup do
108 ffi.C.poll(nil, 0, 10)
113 function c_str(text_in)
115 local c_str = ffi.new("char[?]", #text+1)
116 ffi.copy(c_str, text)
120 function ip46(addr_text)
121 local out = ffi.new("char [200]")
124 local is_ip6 = ffi.C.inet_pton(AF_INET6, c_str(addr_text), out)
126 return ffi.string(out, 16), true
128 local is_ip4 = ffi.C.inet_pton(AF_INET, c_str(addr_text), out)
130 return (string.rep("4", 12).. ffi.string(out, 4)), false
134 function pty_master_open()
135 local fd = ffi.C.posix_openpt(O_RDWR)
138 local p = ffi.C.ptsname(fd)
139 print("PTS:" .. ffi.string(p))
140 return fd, ffi.string(p)
143 function pty_run(cmd)
144 local master_fd, pts_name = pty_master_open()
145 local child_pid = ffi.C.fork()
146 if (child_pid == -1) then
147 print("Error fork()ing")
151 if child_pid ~= 0 then
153 return master_fd, child_pid
157 if (ffi.C.setsid() == -1) then
158 print("Child error setsid")
162 ffi.C.close(master_fd)
164 local slave_fd = ffi.C.open(c_str(pts_name), O_RDWR)
165 if slave_fd == -1 then
166 print("Child can not open slave fd")
170 ffi.C.dup2(slave_fd, 0)
171 ffi.C.dup2(slave_fd, 1)
172 ffi.C.dup2(slave_fd, 2)
177 local buf = ffi.new("char[1]")
178 local nread= ffi.C.read(0, buf, 1)
179 -- print("\nREADCH : " .. string.char(buf[0]))
180 return string.char(buf[0])
183 function stdout_write(str)
184 ffi.C.write(1, c_str(str), #str)
189 split = function(str, pat)
190 local t = {} -- NOTE: use {n = 0} in Lua-5.0
191 local fpat = "(.-)" .. pat
194 local s, e, cap = str:find(fpat, 1)
196 if s ~= 1 or cap ~= "" then
200 s, e, cap = str:find(fpat, last_end)
202 if last_end <= #str then
203 cap = str:sub(last_end)
214 os.execute("stty -icanon min 1 -echo")
219 os.execute("stty icanon echo")
226 rl.history_length = 1
228 rl.hide_cmd = function()
229 local bs = string.char(8) .. " " .. string.char(8)
230 for i = 1, #rl.command do
235 rl.show_cmd = function()
237 stdout_write(rl.command)
241 rl.store_history = function(cmd)
245 rl.history[rl.history_length] = cmd
246 rl.history_length = rl.history_length + 1
247 rl.history_index = rl.history_length
248 rl.history[rl.history_length] = ""
251 rl.readln = function(stdin_select_fn, batch_cmd, batch_when, batch_expect)
253 local need_prompt = true
256 if not rl.rawmode then
261 local indent_value = #rl.prompt + #rl.command
263 stdout_write(rl.prompt)
264 stdout_write(rl.command)
267 if type(stdin_select_fn) == "function" then
268 while not stdin_select_fn(indent_value, batch_cmd, batch_when, batch_expect) do
269 stdout_write(rl.prompt)
270 stdout_write(rl.command)
271 indent_value = #rl.prompt + #rl.command
273 if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
274 stdout_write("\n" .. rl.prompt .. batch_cmd .. "\n")
276 expect_done(batch_expect)
278 return batch_cmd, batch_expect
282 if ch:byte(1) == 27 then
286 if ch2:byte(1) == 91 then
288 local b = ch3:byte(1)
298 -- print("Byte: " .. ch3:byte(1))
310 elseif ch == "\t" then
311 if rl.tab_complete then
316 elseif ch == "\n" then
319 elseif ch == "\004" then
323 elseif ch == string.char(127) then
324 if rl.command ~= "" then
325 stdout_write(string.char(8) .. " " .. string.char(8))
326 rl.command = string.sub(rl.command, 1, -2)
332 if rl.history_index == #rl.history then
333 rl.history[rl.history_index] = rl.command
335 if rl.history_index > 1 then
336 rl.history_index = rl.history_index - 1
337 rl.command = rl.history[rl.history_index]
340 elseif ch == "DOWN" then
342 if rl.history_index < rl.history_length then
343 rl.history_index = rl.history_index + 1
344 rl.command = rl.history[rl.history_index]
350 rl.command = rl.command .. ch
354 rl.store_history(rl.command)
363 local select_fds = {}
366 local line_erased = false
368 function erase_line(indent)
369 if not line_erased then
371 stdout_write(string.rep(string.char(8), indent)..string.rep(" ", indent)..string.rep(string.char(8), indent))
375 function do_select_stdin(indent, batch_cmd, batch_when, batch_expect)
377 local nfds = 1+#select_fds
378 local pfds = ffi.new("struct pollfd[?]", nfds)
382 for i = 1,#select_fds do
383 pfds[i].fd = select_fds[i].fd
387 if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
390 while ffi.C.poll(pfds, nfds, 10) == 0 do
391 if batch_cmd and ((os_time() > batch_when) or (batch_expect and expect_success(batch_expect, buf, 0))) then
399 if pfds[0].revents == 1 then
402 for i = 1,#select_fds do
403 if(pfds[i].revents > 0) then
404 if pfds[i].fd ~= select_fds[i].fd then
405 print("File descriptors unequal", pfds[i].fd, select_fds[i].fd)
407 select_fds[i].cb(select_fds[i], pfds[i].revents, indent)
413 local buf = ffi.new("char [32768]")
415 function session_stdout_write(prefix, data)
416 data = prefix .. data:gsub("\n", "\n"..prefix):gsub("\n"..prefix.."$", "\n")
421 function expect_success(sok, buf, nread)
422 local expect_buf_sz = ffi.sizeof(sok.expect_buf) - 128
423 local expect_buf_avail = expect_buf_sz - sok.expect_buf_idx
424 -- print("EXPECT_SUCCESS: nread ".. tostring(nread).. " expect_buf_idx: " .. tostring(sok.expect_buf_idx) .. " expect_buf_avail: " .. tostring(expect_buf_avail) )
425 if expect_buf_avail < 0 then
426 print "EXPECT BUFFER OVERRUN ALREADY"
429 if expect_buf_avail < nread then
430 if (nread >= ffi.sizeof(sok.expect_buf)) then
431 print("Read too large of a chunk to fit into expect buffer")
434 local delta = nread - expect_buf_avail
436 ffi.C.memmove(sok.expect_buf, sok.expect_buf + delta, expect_buf_sz - delta)
437 sok.expect_buf_idx = sok.expect_buf_idx - delta
438 expect_buf_avail = nread
440 if sok.expect_buf_idx + nread > expect_buf_sz then
441 print("ERROR, I have just overrun the buffer !")
444 ffi.C.memcpy(sok.expect_buf + sok.expect_buf_idx, buf, nread)
445 sok.expect_buf_idx = sok.expect_buf_idx + nread
446 if sok.expect_str == nil then
449 local match_p = ffi.C.memmem(sok.expect_buf, sok.expect_buf_idx, sok.expect_str, sok.expect_str_len)
450 if match_p ~= nil then
456 function expect_done(sok)
457 local expect_buf_sz = ffi.sizeof(sok.expect_buf) - 128
458 if not sok.expect_str then
461 local match_p = ffi.C.memmem(sok.expect_buf, sok.expect_buf_idx, sok.expect_str, sok.expect_str_len)
462 if match_p ~= nil then
463 if sok.expect_cb then
466 local match_idx = ffi.cast("char *", match_p) - ffi.cast("char *", sok.expect_buf)
467 ffi.C.memmove(sok.expect_buf, ffi.cast("char *", match_p) + sok.expect_str_len, expect_buf_sz - match_idx - sok.expect_str_len)
468 sok.expect_buf_idx = match_idx + sok.expect_str_len
469 sok.expect_success = true
472 sok.expect_str_len = 0
477 function slave_events(sok, revents, indent)
479 local nread = ffi.C.read(fd, buf, ffi.sizeof(buf)-128)
480 local idx = nread - 1
481 while idx >= 0 and buf[idx] ~= 10 do
486 session_stdout_write(sok.prefix, sok.buf .. ffi.string(buf, idx+1))
489 sok.buf = sok.buf .. ffi.string(buf+idx+1, nread-idx-1)
490 -- print("\nRead: " .. tostring(nread))
491 -- stdout_write(ffi.string(buf, nread))
492 if expect_success(sok, buf, nread) then
499 function start_session(name)
500 local mfd, cpid = pty_run("/bin/bash")
501 local sok = { ["fd"] = mfd, ["cb"] = slave_events, ["buf"] = "", ["prefix"] = name .. ":", ["expect_buf"] = ffi.new("char [165536]"), ["expect_buf_idx"] = 0, ["expect_str"] = nil }
502 table.insert(select_fds, sok)
506 function command_transform(exe)
507 if exe == "break" then
513 function session_write(a_session, a_str)
514 if has_session(a_session) then
515 return tonumber(ffi.C.write(sessions[a_session].fd, c_str(a_str), #a_str))
521 function session_exec(a_session, a_cmd)
522 local exe = command_transform(a_cmd) .. "\n"
523 session_write(a_session, exe)
526 function session_cmd(ui, a_session, a_cmd)
527 if not has_session(a_session) then
528 stdout_write("ERR: No such session '" .. tostring(a_session) .. "'\n")
531 if a_session == "lua" then
532 local func, msg = loadstring(ui.lua_acc .. a_cmd)
533 -- stdout_write("LOADSTR: " .. vpp.dump({ ret, msg }) .. "\n")
534 if not func and string.match(msg, "<eof>") then
535 if a_session ~= ui.in_session then
536 stdout_write("ERR LOADSTR: " .. tostring(msg) .. "\n")
539 ui.lua_acc = ui.lua_acc .. a_cmd .. "\n"
543 local ret, msg = pcall(func)
547 stdout_write("ERR: " .. msg .. "\n")
551 session_exec(a_session, a_cmd)
552 if ui.session_cmd_delay then
553 return { "delay", ui.session_cmd_delay }
559 function has_session(a_session)
560 if a_session == "lua" then
563 return (sessions[a_session] ~= nil)
566 function command_match(list, input, output)
567 for i, v in ipairs(list) do
569 m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] = string.match(input, v[1])
570 -- print("MATCH: ", vpp.dump(m))
573 output["result_index"] = i
580 function cmd_spawn_shell(ui, a_arg)
581 start_session(a_arg[1])
585 function cmd_run_cmd(ui, a_arg)
586 local a_sess = a_arg[1]
587 local a_cmd = a_arg[2]
588 return session_cmd(ui, a_sess, a_cmd)
591 function cmd_cd(ui, a_arg)
592 local a_sess = a_arg[1]
593 if has_session(a_sess) then
594 ui.in_session = a_sess
597 stdout_write("ERR: Unknown session '".. tostring(a_sess) .. "'\n")
602 function cmd_sleep(ui, a_arg)
603 return { "delay", tonumber(a_arg[1]) }
606 function cmd_expect(ui, a_arg)
607 local a_sess = a_arg[1]
608 local a_expect = a_arg[2]
609 local sok = sessions[a_sess]
611 stdout_write("ERR: unknown session '" .. tostring(a_sess) .. "'\n")
614 sok.expect_str = c_str(a_expect)
615 sok.expect_str_len = #a_expect
616 return { "expect", a_sess }
619 function cmd_info(ui, a_arg)
620 local a_sess = a_arg[1]
621 local sok = sessions[a_sess]
623 stdout_write("ERR: unknown session '" .. tostring(a_sess) .. "'\n")
626 print("Info for session " .. tostring(a_sess) .. "\n")
627 print("Expect buffer index: " .. tostring(sok.expect_buf_idx))
628 print("Expect buffer: '" .. tostring(ffi.string(sok.expect_buf, sok.expect_buf_idx)) .. "'\n")
629 if sok.expect_str then
630 print("Expect string: '" .. tostring(ffi.string(sok.expect_str, sok.expect_str_len)) .. "'\n")
632 print("Expect string not set\n")
636 function cmd_echo(ui, a_arg)
637 local a_data = a_arg[1]
638 print("ECHO: " .. tostring(a_data))
641 main_command_table = {
642 { "^shell ([a-zA-Z0-9_]+)$", cmd_spawn_shell },
643 { "^run ([a-zA-Z0-9_]+) (.+)$", cmd_run_cmd },
644 { "^cd ([a-zA-Z0-9_]+)$", cmd_cd },
645 { "^sleep ([0-9]+)$", cmd_sleep },
646 { "^expect ([a-zA-Z0-9_]+) (.-)$", cmd_expect },
647 { "^info ([a-zA-Z0-9_]+)$", cmd_info },
648 { "^echo (.-)$", cmd_echo }
653 function ui_set_prompt(ui)
654 if ui.in_session then
655 if ui.in_session == "lua" then
656 if #ui.lua_acc > 0 then
657 ui.r.prompt = ui.in_session .. ">>"
659 ui.r.prompt = ui.in_session .. ">"
662 ui.r.prompt = ui.in_session .. "> "
670 function ui_run_command(ui, cmd)
671 -- stdout_write("Command: " .. tostring(cmd) .. "\n")
673 if ui.in_session then
675 if cmd == "^D^D^D" then
679 ret = session_cmd(ui, ui.in_session, cmd)
691 if command_match(main_command_table, cmd, out) then
692 local i = out.result_index
694 if main_command_table[i][2] then
695 ret = main_command_table[i][2](ui, m)
699 if not cmd or cmd == "quit" then
708 ui.r = readln.reader()
710 ui.session_cmd_delay = 0.3
715 -- a helper function which always returns nil
716 local no_next_line = function() return nil end
718 -- a function which returns the next batch line
719 local next_line = no_next_line
721 local batchfile = arg[1]
724 local f = io.lines(batchfile)
725 next_line = function()
730 next_line = no_next_line
731 session_stdout_write(batchfile .. ":", "End of batch\n")
739 local batch_expect = nil
741 local prompt = ui_set_prompt(ui)
742 local batch_cmd = next_line()
743 local cmd, expect_sok = ui.r.readln(do_select_stdin, batch_cmd, batch_when, batch_expect)
744 if expect_sok and not expect_success(expect_sok, buf, 0) then
745 if not cmd_ret and next_line ~= no_next_line then
746 print("ERR: expect timeout\n")
747 next_line = no_next_line
750 local cmd_ret = ui_run_command(ui, cmd)
751 if not cmd_ret and next_line ~= no_next_line then
752 print("ERR: Error during batch execution\n")
753 next_line = no_next_line
756 if cmd_ret == "quit" then
761 if type(cmd_ret) == "table" then
762 if cmd_ret[1] == "delay" then
763 batch_when = os_time() + tonumber(cmd_ret[2])
765 if cmd_ret[1] == "expect" then
766 batch_expect = sessions[cmd_ret[2]]
767 batch_when = os_time() + 15