util.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. -- Writes all lines from the file input to the file output except those starting with prefix
  2. -- Doesn't close the output file, but returns the file object
  3. local function do_filter_prefix(input, output, prefix)
  4. local f = io.open(output, 'w+')
  5. local l = prefix:len()
  6. for line in io.lines(input) do
  7. if line:sub(1, l) ~= prefix then
  8. f:write(line, '\n')
  9. end
  10. end
  11. return f
  12. end
  13. local function escape_args(ret, arg0, ...)
  14. if not arg0 then
  15. return ret
  16. end
  17. return escape_args(ret .. "'" .. string.gsub(arg0, "'", "'\\''") .. "' ", ...)
  18. end
  19. local os = os
  20. local string = string
  21. local tonumber = tonumber
  22. local nixio = require 'nixio'
  23. local sysconfig = require 'gluon.sysconfig'
  24. module 'gluon.util'
  25. function exec(...)
  26. return os.execute(escape_args('', ...))
  27. end
  28. -- Removes all lines starting with a prefix from a file, optionally adding a new one
  29. function replace_prefix(file, prefix, add)
  30. local tmp = file .. '.tmp'
  31. local f = do_filter_prefix(file, tmp, prefix)
  32. if add then
  33. f:write(add)
  34. end
  35. f:close()
  36. os.rename(tmp, file)
  37. end
  38. function lock(file)
  39. exec('lock', file)
  40. end
  41. function unlock(file)
  42. exec('lock', '-u', file)
  43. end
  44. function node_id()
  45. return string.gsub(sysconfig.primary_mac, ':', '')
  46. end
  47. -- Generates a (hopefully) unique MAC address
  48. -- The first parameter defines the function and the second
  49. -- parameter an ID to add to the MAC address
  50. -- Functions and IDs defined so far:
  51. -- (1, 0): WAN (for mesh-on-WAN)
  52. -- (1, 1): LAN (for mesh-on-LAN)
  53. -- (2, n): client interface for the n'th radio
  54. -- (3, n): adhoc interface for n'th radio
  55. -- (4, 0): mesh VPN
  56. function generate_mac(f, i)
  57. local m1, m2, m3, m4, m5, m6 = string.match(sysconfig.primary_mac, '(%x%x):(%x%x):(%x%x):(%x%x):(%x%x):(%x%x)')
  58. m1 = nixio.bit.bor(tonumber(m1, 16), 0x02)
  59. m2 = (tonumber(m2, 16)+f) % 0x100
  60. m3 = (tonumber(m3, 16)+i) % 0x100
  61. return string.format('%02x:%02x:%02x:%s:%s:%s', m1, m2, m3, m4, m5, m6)
  62. end