Advertisement
Guest User

Untitled

a guest
May 27th, 2017
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 47.56 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # Copyright (C) 2006-2007 Red Hat, Inc.
  4.  
  5. import sys, os, pwd
  6. from select import select
  7. from stat import S_ISREG
  8. import types
  9. import xml
  10. import xml.dom
  11.  
  12. sys.path.extend((
  13.         '/usr/lib/luci/zope/lib/python',
  14.         '/usr/lib/luci/zope/lib/python/Products',
  15.         '/usr/lib64/luci/zope/lib/python',
  16.         '/usr/lib64/luci/zope/lib/python/Products',
  17.         '/usr/lib64/luci/zope/lib64/python',
  18.         '/usr/lib64/luci/zope/lib64/python/Products',
  19.         '/usr/lib64/zope/lib64/python',
  20.         '/usr/lib64/zope/lib/python',
  21.         '/usr/lib/zope/lib/python',
  22.         '/usr/lib64/zope/lib/python/Products',
  23.         '/usr/lib64/zope/lib64/python/Products',
  24.         '/usr/lib/zope/lib/python/Products'
  25. ))
  26.  
  27. from Products import __path__
  28. for pdir in ['/usr/lib/luci/zope/lib/python/Products',
  29.           '/usr/lib64/luci/zope/lib/python/Products',
  30.           '/usr/lib64/luci/zope/lib64/python/Products',
  31.           '/usr/lib64/zope/lib/python/Products',
  32.           '/usr/lib64/zope/lib64/python/Products',
  33.           '/usr/lib/zope/lib/python/Products']:
  34.         if os.path.isdir(pdir):
  35.                 __path__.append(pdir)
  36.  
  37. LUCI_INIT_DEBUG = 0
  38.  
  39. LUCI_USER  = 'luci'
  40. LUCI_GROUP = 'luci'
  41.  
  42. LUCI_HOME_DIR       = '/var/lib/luci'
  43. LUCI_DB_PATH        = LUCI_HOME_DIR + '/var/Data.fs'
  44. LUCI_CERT_DIR       = LUCI_HOME_DIR + '/var/certs/'
  45. LUCI_PEERS_DIR      = LUCI_CERT_DIR + 'peers/'
  46. LUCI_BACKUP_DIR     = LUCI_HOME_DIR + '/var'
  47. LUCI_BACKUP_PATH    = LUCI_BACKUP_DIR + '/luci_backup.xml'
  48. LUCI_ADMIN_SET_PATH = LUCI_HOME_DIR + '/.default_password_has_been_reset'
  49.  
  50. SSL_PRIVKEY_NAME       = 'privkey.pem'
  51. SSL_PUBKEY_NAME        = 'cacert.pem'
  52. SSL_HTTPS_PRIVKEY_NAME = 'https.key.pem'
  53. SSL_HTTPS_PUBKEY_NAME  = 'https.pem'
  54. SSL_KEYCONFIG_NAME     = 'cacert.config'
  55.  
  56. SSL_PRIVKEY_PATH       = LUCI_CERT_DIR + SSL_PRIVKEY_NAME
  57. SSL_PUBKEY_PATH        = LUCI_CERT_DIR + SSL_PUBKEY_NAME
  58. SSL_HTTPS_PRIVKEY_PATH = LUCI_CERT_DIR + SSL_HTTPS_PRIVKEY_NAME
  59. SSL_HTTPS_PUBKEY_PATH  = LUCI_CERT_DIR + SSL_HTTPS_PUBKEY_NAME
  60. SSL_KEYCONFIG_PATH     = LUCI_CERT_DIR + SSL_KEYCONFIG_NAME
  61.  
  62. # only root should run this
  63. if os.getuid() != 0:
  64.         sys.stderr.write('Only the \'root\' user can run %s\n' % sys.argv[0])
  65.         sys.stderr.write('Try again with root privileges.\n')
  66.         sys.exit(2)
  67.  
  68. ssl_key_data = [
  69.         { 'id'  : SSL_PRIVKEY_PATH,
  70.           'name': SSL_PRIVKEY_NAME,
  71.           'type': 'private',
  72.           'mode': 0600 },
  73.         { 'id'  : SSL_HTTPS_PRIVKEY_PATH,
  74.           'name': SSL_HTTPS_PRIVKEY_NAME,
  75.           'type': 'private',
  76.           'mode': 0600 },
  77.         { 'id'  : SSL_PUBKEY_PATH,
  78.           'name': SSL_PUBKEY_NAME,
  79.           'type': 'public',
  80.           'mode': 0644 },
  81.         { 'id'  : SSL_HTTPS_PUBKEY_PATH,
  82.           'name': SSL_HTTPS_PUBKEY_NAME,
  83.           'type': 'public',
  84.           'mode': 0644 },
  85.         { 'id'  : SSL_KEYCONFIG_PATH,
  86.           'name': SSL_KEYCONFIG_NAME,
  87.           'type': 'config',
  88.           'mode': 0644 }
  89. ]
  90.  
  91. for name in os.listdir(LUCI_PEERS_DIR):
  92.         cert_path = LUCI_PEERS_DIR + name
  93.         if S_ISREG(os.stat(cert_path).st_mode):
  94.                 ssl_key_data.append({
  95.                                      'id'   : cert_path,
  96.                                      'name' : cert_path.lstrip(LUCI_CERT_DIR),
  97.                                      'type' : 'public',
  98.                                      'mode' : 0644})
  99.  
  100. #null = file(os.devnull, 'rwb+', 0)   - available on python 2.4 and above!!!
  101. null = file('/dev/null', 'rwb+', 0)
  102. orig_stderr = sys.stderr
  103.  
  104. if LUCI_INIT_DEBUG:
  105.         verbose = sys.stderr
  106. else:
  107.         verbose = null
  108.  
  109.  
  110.  
  111. def get_luci_uid_gid():
  112.         try:
  113.                 luci = pwd.getpwnam(LUCI_USER)[2:4]
  114.                 if not luci:
  115.                         raise
  116.                 if len(luci) != 2:
  117.                         raise
  118.                 return luci
  119.         except:
  120.                 msg = 'Cannot find the "%s" user.\n' % LUCI_USER
  121.                 sys.stderr.write(msg)
  122.                 raise Exception, msg
  123.  
  124.  
  125. def set_default_passwd_reset_flag():
  126.         # set flag marking admin password has been set
  127.  
  128.         try:
  129.                 uid, gid = get_luci_uid_gid()
  130.         except:
  131.                 sys.stderr.write('Unable to find the luci user\'s UID\n')
  132.                 return False
  133.  
  134.         try:
  135.                 open(LUCI_ADMIN_SET_PATH, 'w').write('True')
  136.         except IOError, e:
  137.                 if e[0] != 2:
  138.                         sys.stderr.write('Unable to open "%s" for writing: %s\n' \
  139.                                 % (LUCI_ADMIN_SET_PATH, e[1]))
  140.                         return False
  141.         except Exception, e:
  142.                 sys.stderr.write('Unable to open "%s" for writing: %s\n' \
  143.                         % (LUCI_ADMIN_SET_PATH, str(e)))
  144.                 return False
  145.  
  146.         os.chown(LUCI_ADMIN_SET_PATH, uid, gid)
  147.         os.chmod(LUCI_ADMIN_SET_PATH, 0640)
  148.         return True
  149.  
  150. def get_default_passwd_reset_flag():
  151.         try:
  152.                 return open(LUCI_ADMIN_SET_PATH, 'r').read(16).strip() == 'True'
  153.         except:
  154.                 return False
  155.         return False
  156.  
  157.  
  158. def read_passwd(prompt, confirm_prompt):
  159.         from getpass import getpass
  160.         while True:
  161.                 s1 = getpass(prompt)
  162.                 if len(s1) < 6:
  163.                         print 'Password has to be at least 6 characters long'
  164.                         continue
  165.                 if ' ' in s1:
  166.                         print 'Spaces are not allowed in passwords'
  167.                         continue
  168.                 s2 = getpass(confirm_prompt)
  169.                 if s1 != s2:
  170.                         print 'Password mismatch, try again'
  171.                         continue
  172.                 return s1
  173.  
  174.  
  175.  
  176. def restore_luci_db_fsattr():
  177.         uid, gid = -1, -1
  178.  
  179.         try:
  180.                 uid, gid = get_luci_uid_gid()
  181.         except:
  182.                 return -1
  183.  
  184.         try:
  185.                 os.chown(LUCI_DB_PATH, uid, gid)
  186.                 os.chmod(LUCI_DB_PATH, 0600)
  187.  
  188.                 for fext in [ '.tmp', '.old', '.index', '.lock' ]:
  189.                         try:
  190.                                 os.chown('%s%s' % (LUCI_DB_PATH, fext), uid, gid)
  191.                                 os.chmod('%s%s' % (LUCI_DB_PATH, fext), 0600)
  192.                         except:
  193.                                 pass
  194.         except Exception, e:
  195.                 sys.stderr.write('Unable to change ownership of the Luci database back to user "%s": %s\n' % (LUCI_USER, str(e)))
  196.                 return -1
  197.  
  198. def set_zope_passwd(user, passwd):
  199.         sys.stderr = null
  200.         from ZODB.FileStorage import FileStorage
  201.         from ZODB.DB import DB
  202.         from OFS.Application import AppInitializer
  203.         import AccessControl
  204.         import AccessControl.User
  205.         from AccessControl.AuthEncoding import SSHADigestScheme
  206.         from AccessControl.SecurityManagement import newSecurityManager
  207.         import transaction
  208.         import App.ImageFile
  209.         # Zope wants to open a www/ok.gif and images/error.gif
  210.         # when you initialize the application object. This keeps
  211.         # the AppInitializer(app).initialize() call below from failing.
  212.         App.ImageFile.__init__ = lambda x, y: None
  213.         sys.stderr = orig_stderr
  214.  
  215.         try:
  216.                 fs = FileStorage(LUCI_DB_PATH)
  217.                 db = DB(fs)
  218.                 conn = db.open()
  219.         except IOError, e:
  220.                 if e[0] == 11:
  221.                         sys.stderr.write('It appears that Luci is running. Please stop Luci before attempting to reset passwords.\n')
  222.                         return -1
  223.                 else:
  224.                         sys.stderr.write('Unable to open the Luci database \"' + LUCI_DB_PATH + '\":' + str(e) + '\n')
  225.                         return -1
  226.         except Exception, e:
  227.                 sys.stderr.write('Unable to open the Luci database \"' + LUCI_DB_PATH + '\":' + str(e) + '\n')
  228.                 return -1
  229.  
  230.         try:
  231.                 sys.stderr = null
  232.                 tempuser = AccessControl.User.UnrestrictedUser('admin', '',
  233.                                         ('manage','Manager', 'Owner', 'View', 'Authenticated'), [])
  234.  
  235.                 newSecurityManager(None, tempuser)
  236.  
  237.                 app = conn.root()['Application']
  238.                 AppInitializer(app).initialize()
  239.                 sys.stderr = orig_stderr
  240.         except:
  241.                 sys.stderr = orig_stderr
  242.                 sys.stderr.write('An error occurred while setting the password for user \"' + user + '\"\n')
  243.                 return -1
  244.  
  245.         ret = -1
  246.         try:
  247.                 pwd_scheme = SSHADigestScheme
  248.                 pwd_hash = '{SSHA}' + pwd_scheme.encrypt(SSHADigestScheme(), passwd)
  249.                 acl_users = app.acl_users.users
  250.                 if len(acl_users):
  251.                         acl_users._user_passwords[user] = pwd_hash
  252.                         transaction.commit()
  253.                         ret = 0
  254.                 else:
  255.                         raise
  256.         except:
  257.                 sys.stderr.write('Unable to set the password for user \"' + user + '\"\n')
  258.  
  259.         conn.close()
  260.         db.pack()
  261.         db.close()
  262.         fs.close()
  263.  
  264.         if restore_luci_db_fsattr():
  265.                 return -1
  266.  
  267.         if user == 'admin' and ret == 0:
  268.                 set_default_passwd_reset_flag()
  269.  
  270.         return ret
  271.  
  272.  
  273. def luci_restore_certs(certList):
  274.         if not certList or len(certList) < 1:
  275.                 sys.stderr.write('Your backup file contains no certificate data. Please check that your backup file is not corrupt.\n')
  276.                 return -1
  277.  
  278.         certList = certList[0].getElementsByTagName('certificate')
  279.         if not certList or len(certList) < 1:
  280.                 sys.stderr.write('Your backup file contains no certificate data. Please check that your backup file is not corrupt.\n')
  281.                 return -1
  282.  
  283.         uid, gid = -1, -1
  284.         try:
  285.                 uid, gid = get_luci_uid_gid()
  286.         except:
  287.                 return -1
  288.  
  289.         for c in certList:
  290.                 path = c.getAttribute('name')
  291.                 if not path:
  292.                         sys.stderr.write('Missing \"name\" field for certificate.\n')
  293.                         return -1
  294.                 path = LUCI_CERT_DIR + str(path)
  295.  
  296.                 mode = c.getAttribute('mode')
  297.                 if not mode:
  298.                         mode = 0600
  299.                 else:
  300.                         mode = int(mode, 8)
  301.  
  302.                 data = c.firstChild
  303.                 if not data or not data.wholeText:
  304.                         sys.stderr.write('\"' + path + '\" has no certificate data.')
  305.                         return -1
  306.  
  307.                 # Because .prettyprint() was called to write the backup..
  308.                 data = data.wholeText.strip()
  309.                 if len(data) < 1:
  310.                         sys.stderr.write('\"' + path + '\" has no certificate data.')
  311.                         return -1
  312.                 data = str(data)
  313.  
  314.                 try:
  315.                         f = file(path, 'wb+')
  316.                 except:
  317.                         sys.stderr.write('Unable to create \" ' + path + '\" for writing.\n')
  318.                         return -1
  319.  
  320.                 os.chmod(path, mode)
  321.                 f.write(data + '\n')
  322.                 os.chown(path, uid, gid)
  323.                 f.close()
  324.         return None
  325.  
  326.  
  327. def luci_restore(argv):
  328.         sys.stderr = null
  329.         from ZODB.FileStorage import FileStorage
  330.         from ZODB.DB import DB
  331.         from OFS.Application import AppInitializer
  332.         import AccessControl
  333.         import AccessControl.User
  334.         from AccessControl.SecurityManagement import newSecurityManager
  335.         import transaction
  336.         import App.ImageFile
  337.         from DateTime import DateTime
  338.         App.ImageFile.__init__ = lambda x, y: None
  339.         sys.stderr = orig_stderr
  340.  
  341.         if len(argv) > 0:
  342.                 dbfn = argv[0]
  343.         else:
  344.                 dbfn = LUCI_DB_PATH
  345.  
  346.         if len(argv) > 1:
  347.                 backupfn = argv[1]
  348.         else:
  349.                 backupfn = LUCI_BACKUP_PATH
  350.  
  351.         try:
  352.                 fs = FileStorage(dbfn)
  353.                 db = DB(fs)
  354.                 db.pack()
  355.                 conn = db.open()
  356.         except IOError, e:
  357.                 if e[0] == 11:
  358.                         sys.stderr.write('It appears that Luci is running. Please stop Luci before attempting to restore your installation.\n')
  359.                         return -1
  360.                 else:
  361.                         sys.stderr.write('Unable to open the Luci database \"' + dbfn + '\":' + str(e) + '\n')
  362.                         return -1
  363.         except Exception, e:
  364.                 sys.stderr.write('Unable to open the Luci database \"' + dbfn + '\":' + str(e) + '\n')
  365.                 return -1
  366.  
  367.         try:
  368.                 node = xml.dom.minidom.parse(backupfn)
  369.         except:
  370.                 sys.stderr.write('Unable to open the Luci backup file \"'+ backupfn +'\"\n')
  371.                 return -1
  372.  
  373.         node = node.getElementsByTagName('luci')
  374.         if not node or len(node) < 1:
  375.                 sys.stderr.write('Backup file is missing the \'luci\' tag\n')
  376.                 return -1
  377.  
  378.         node = node[0].getElementsByTagName('backupData')
  379.         if not node or len(node) < 1:
  380.                 sys.stderr.write('Backup file is missing the \'backupData\' tag\n')
  381.                 return -1
  382.         node = node[0]
  383.  
  384.         try:
  385.                 sys.stderr = null
  386.                 tempuser = AccessControl.User.UnrestrictedUser('admin', '',
  387.                                         ('manage','Manager', 'Owner', 'View', 'Authenticated'), [])
  388.  
  389.                 newSecurityManager(None, tempuser)
  390.  
  391.                 app = conn.root()['Application']
  392.                 AppInitializer(app).initialize()
  393.                 sys.stderr = orig_stderr
  394.         except:
  395.                 sys.stderr = orig_stderr
  396.                 sys.stderr.write('An error occurred while initializing the Luci installation for restoration from backup\n')
  397.                 return -1
  398.  
  399.         try:
  400.                 acl_users = app.acl_users.users
  401.                 portal_mem = app.luci.portal_membership
  402.                 portal_reg = app.luci.portal_registration
  403.                 if not (acl_users and len(acl_users) and portal_mem and portal_reg):
  404.                         raise
  405.         except:
  406.                 sys.stderr.write('Your Luci installation appears to be corrupt.\n')
  407.                 return -1
  408.  
  409.         userList = node.getElementsByTagName('userList')
  410.         if not userList or len(userList) < 1:
  411.                 sys.stderr.write('Your backup file contains no users. At the very least, the admin user must exist. Please check that your backup file is not
  412. corrupt.\n')
  413.                 return -1
  414.  
  415.         userList = userList[0].getElementsByTagName('user')
  416.         if not userList or len(userList) < 1:
  417.                 sys.stderr.write('Your backup file contains no users. At the very least, the admin user must exist. Please check that your backup file is not
  418. corrupt.\n')
  419.                 return -1
  420.  
  421.         for u in userList:
  422.                 id = u.getAttribute('id')
  423.                 if not id:
  424.                         transaction.abort()
  425.                         sys.stderr.write('Missing ID for user\n')
  426.                         return -1
  427.                 id = str(id)
  428.  
  429.                 passwd = u.getAttribute('passwd')
  430.                 if not passwd:
  431.                         transaction.abort()
  432.                         sys.stderr.write('Missing password for user \"' + id + '\"\n')
  433.                         return -1
  434.                 passwd = str(passwd)
  435.  
  436.                 if id == 'admin':
  437.                         try:
  438.                                 acl_users._user_passwords['admin'] = passwd
  439.                         except:
  440.                                 transaction.abort()
  441.                                 sys.stderr.write('Unable to restore admin password.')
  442.                                 return -1
  443.                 else:
  444.                         email = u.getAttribute('email')
  445.                         if not email:
  446.                                 email = id + '@luci.example.org'
  447.                         else:
  448.                                 email = str(email)
  449.  
  450.                         props = {
  451.                                 'username': id,
  452.                                 'roles': [ 'Member' ],
  453.                                 'domains': [],
  454.                                 'email': email,
  455.                                 'must_change_password': False
  456.                         }
  457.  
  458.                         login_time = u.getAttribute('login_time')
  459.                         if login_time:
  460.                                 props['login_time'] = DateTime(str(login_time))
  461.  
  462.                         last_login_time = u.getAttribute('last_login_time')
  463.                         if last_login_time:
  464.                                 props['last_login_time'] = DateTime(str(last_login_time))
  465.  
  466.                         must_change_passwd = u.getAttribute('must_change_password')
  467.                         if must_change_passwd:
  468.                                 must_change_passwd = str(must_change_passwd)
  469.                                 if must_change_passwd == 'True' or '1':
  470.                                         props['must_change_password'] = True
  471.  
  472.                         portal_reg.addMember(id, passwd, props)
  473.  
  474.                         member = portal_mem.getMemberById(id)
  475.                         if not member:
  476.                                 transaction.abort()
  477.                                 sys.stderr.write('An error occurred while restoring the user \"' + id + '\"\n')
  478.                                 return -1
  479.  
  480.                         try:
  481.                                 aclu = app.luci.acl_users.source_users
  482.                                 if aclu and len(aclu):
  483.                                         aclu._user_passwords[id] = passwd
  484.                                 else:
  485.                                         raise
  486.                         except:
  487.                                 transaction.abort()
  488.                                 sys.stderr.write('An error occurred while restoring the password for user \"' + id + '\"\n')
  489.                                 return -1
  490.                         verbose.write('Added user \"' + id + '\"\n')
  491.         transaction.commit()
  492.  
  493.         try:
  494.                 x = app.luci.systems.storage
  495.                 if not x:
  496.                         raise
  497.         except:
  498.                 transaction.abort()
  499.                 sys.stderr.write('Cannot find the Luci storage systems directory. Your Luci installation may be corrupt.\n')
  500.                 return -1
  501.  
  502.         systemList = node.getElementsByTagName('systemList')
  503.         if not systemList or len(systemList) < 1:
  504.                 verbose.write('No storage systems to add\n')
  505.         else:
  506.                 systemList = systemList[0].getElementsByTagName('system')
  507.                 if len(systemList) < 1:
  508.                         verbose.write('No storage systems to add\n')
  509.  
  510.         for s in systemList:
  511.                 id = s.getAttribute('id')
  512.                 if not id:
  513.                         transaction.abort()
  514.                         sys.stderr.write('Missing ID for storage system. Your backup may be corrupt.\n')
  515.                         return -1
  516.                 id = str(id)
  517.                 try:
  518.                         title = str(s.getAttribute('title'))
  519.                 except:
  520.                         title = ''
  521.  
  522.                 x.manage_addFolder(id, title)
  523.                 try:
  524.                         new_system = app.luci.systems.storage.get(id)
  525.                         if not new_system:
  526.                                 raise
  527.                         new_system.manage_acquiredPermissions([])
  528.                         new_system.manage_role('View',
  529.                                 ['Access contents information', 'View'])
  530.                 except:
  531.                         transaction.abort()
  532.                         sys.stderr.write('An error occurred while restoring storage system \"' + id + '\"\n')
  533.                         return -1
  534.  
  535.                 userPerms = s.getElementsByTagName('permList')
  536.                 if not userPerms or len(userPerms) < 1:
  537.                         verbose.write('Added storage system \"' + id + '\"\n')
  538.                         continue
  539.                 userPerms = userPerms[0].getElementsByTagName('ref')
  540.                 for i in userPerms:
  541.                         newuser = i.getAttribute('name')
  542.                         if not newuser:
  543.                                 continue
  544.                         try:
  545.                                 new_system.manage_setLocalRoles(newuser, ['View'])
  546.                                 verbose.write('Added view permission to storage system \"' + id + '\" for \"' + newuser + '\"\n')
  547.                         except:
  548.                                 sys.stderr.write('An error occurred while restoring permission for storage system \"' + id + '\" for user \"' + newuser + '\"\
  549. n')
  550.  
  551.                 verbose.write('Added storage system \"' + id + '\"\n')
  552.                 transaction.commit()
  553.  
  554.         try:
  555.                 x = app.luci.systems.cluster
  556.                 if not x:
  557.                         raise
  558.         except:
  559.                 transaction.abort()
  560.                 sys.stderr.write('Cannot find the Luci cluster directory. Your Luci installation may be corrupt.\n')
  561.                 return -1
  562.  
  563.         clusterList = node.getElementsByTagName('clusterList')
  564.         if not clusterList or len(clusterList) < 1:
  565.                 verbose.write('No clusters to add\n')
  566.         else:
  567.                 clusterList = clusterList[0].getElementsByTagName('cluster')
  568.                 if len(clusterList) < 1:
  569.                         verbose.write('No clusters to add\n')
  570.  
  571.         for c in clusterList:
  572.                 id = c.getAttribute('id')
  573.                 if not id:
  574.                         transaction.abort()
  575.                         sys.stderr.write('Cluster element is missing id\n')
  576.                         return -1
  577.                 id = str(id)
  578.  
  579.                 title = c.getAttribute('title')
  580.                 if not title:
  581.                         title = ''
  582.                 else:
  583.                         title = str(title)
  584.  
  585.                 try:
  586.                         x.manage_addFolder(id, title)
  587.                         new_cluster = app.luci.systems.cluster.get(id)
  588.  
  589.                         if not new_cluster:
  590.                                 raise
  591.                         new_cluster.manage_acquiredPermissions([])
  592.                         new_cluster.manage_role('View',
  593.                                 ['Access contents information', 'View'])
  594.                 except:
  595.                         transaction.abort()
  596.                         sys.stderr.write('An error occurred while restoring the cluster \"' + id + '\"\n')
  597.                         return -1
  598.  
  599.                 viewperm = list()
  600.  
  601.                 userPerms = c.getElementsByTagName('permList')
  602.                 if userPerms and len(userPerms) > 0:
  603.                         userPerms = userPerms[0].getElementsByTagName('ref')
  604.                         for i in userPerms:
  605.                                 newuser = i.getAttribute('name')
  606.                                 if not newuser:
  607.                                         continue
  608.                                 newuser = str(newuser)
  609.  
  610.                                 try:
  611.                                         new_cluster.manage_setLocalRoles(newuser, ['View'])
  612.                                         verbose.write('Added view permission to cluster \"' + id + '\" for \"' + newuser + '\"\n')
  613.                                 except:
  614.                                         sys.stderr.write('An error occurred while restoring permission for cluster \"' + id + '\" for user \"' + newuser + '\"
  615. \n')
  616.                                 viewperm.append(newuser)
  617.  
  618.                 clusterSystems = c.getElementsByTagName('csystemList')
  619.                 if not clusterSystems or len(clusterSystems) < 1:
  620.                         verbose.write('Cluster \"' + id + '\" has no storage systems\n')
  621.                 else:
  622.                         clusterSystems = clusterSystems[0].getElementsByTagName('csystem')
  623.                         for i in clusterSystems:
  624.                                 newsys = i.getAttribute('id')
  625.                                 if not newsys:
  626.                                         transaction.abort()
  627.                                         sys.stderr.write('Storage system missing name for cluster \"' + id + '\"\n')
  628.                                         return -1
  629.  
  630.                                 newsys = str(newsys)
  631.                                 stitle = i.getAttribute('title')
  632.                                 if not stitle:
  633.                                         stitle = ''
  634.                                 else:
  635.                                         stitle = str(stitle)
  636.  
  637.                                 try:
  638.                                         new_cluster.manage_addFolder(newsys, stitle)
  639.                                         newcs = app.luci.systems.cluster.get(id).get(newsys)
  640.                                         if not newcs:
  641.                                                 raise
  642.                                         newcs.manage_acquiredPermissions([])
  643.                                         newcs.manage_role('View',
  644.                                                 ['Access contents information', 'View'])
  645.                                 except:
  646.                                         transaction.abort()
  647.                                         sys.stderr.write('An error occurred while restoring the storage system \"' + newsys + '\" for cluster \"' + id + '\"\n
  648. ')
  649.                                         return -1
  650.                                 transaction.commit()
  651.  
  652.                                 try:
  653.                                         for i in viewperm:
  654.                                                 newcs.manage_setLocalRoles(i, ['View'])
  655.                                                 verbose.write('Added view permission to cluster system \"' + newsys + '\" for \"' + i + '\"\n')
  656.                                 except:
  657.                                         transaction.abort()
  658.                                         sys.stderr.write('An error occurred while restoring permissions for cluster system \"' + newsys + '\" in cluster \"' +
  659.  id + '\" for user \"' + i + '\"\n')
  660.                                         return -1
  661.  
  662.                                 verbose.write('Added storage system \"' + newsys + '\" for cluster \"' + id + '\"\n')
  663.  
  664.                 verbose.write('Added cluster \"' + id + '\"\n')
  665.                 transaction.commit()
  666.  
  667.         transaction.commit()
  668.         conn.close()
  669.         db.pack()
  670.         db.close()
  671.         fs.close()
  672.  
  673.         certList = node.getElementsByTagName('certificateList')
  674.         if not certList or len(certList) < 1:
  675.                 sys.stderr.write('No certificate data was found.\n')
  676.                 return -1
  677.  
  678.         if luci_restore_certs(certList):
  679.                 sys.stderr.write('An error occurred while restoring certificate data.\n')
  680.                 return -1
  681.  
  682.         return 0
  683.  
  684. # This function's ability to work is dependent
  685. # upon the structure of @obj_dict
  686. def dataToXML(doc, obj_dict, tltag):
  687.         node = doc.createElement(tltag)
  688.         for i in obj_dict:
  689.                 if isinstance(obj_dict[i], types.DictType):
  690.                         if i[-4:] == 'List':
  691.                                 tagname = i
  692.                         else:
  693.                                 tagname = tltag[:-4]
  694.                         temp = dataToXML(doc, obj_dict[i], tagname)
  695.                         node.appendChild(temp)
  696.                 elif isinstance(obj_dict[i], types.StringType) or isinstance(obj_dict[i], types.IntType):
  697.                         node.setAttribute(i, str(obj_dict[i]))
  698.                 elif isinstance(obj_dict[i], types.ListType):
  699.                         if len(obj_dict[i]) < 1:
  700.                                 continue
  701.                         temp = doc.createElement(i)
  702.                         for x in obj_dict[i]:
  703.                                 t = doc.createElement('ref')
  704.                                 t.setAttribute('name', x)
  705.                                 temp.appendChild(t.cloneNode(True))
  706.                         node.appendChild(temp.cloneNode(True))
  707.         return node.cloneNode(True)
  708.  
  709. def luci_backup(argv):
  710.         sys.stderr = null
  711.         from ZODB.FileStorage import FileStorage
  712.         from ZODB.DB import DB
  713.         from OFS.Application import AppInitializer
  714.         import AccessControl
  715.         import AccessControl.User
  716.         from AccessControl.SecurityManagement import newSecurityManager
  717.         import transaction
  718.         from CMFPlone.utils import getToolByName
  719.         import App.ImageFile
  720.         App.ImageFile.__init__ = lambda x, y: None
  721.         sys.stderr = orig_stderr
  722.  
  723.         if len(argv) > 0:
  724.                 dbfn = argv[0]
  725.         else:
  726.                 dbfn = LUCI_DB_PATH
  727.  
  728.         try:
  729.                 fs = FileStorage(dbfn)
  730.                 db = DB(fs)
  731.                 db.pack()
  732.                 conn = db.open()
  733.         except IOError, e:
  734.                 if e[0] == 11:
  735.                         sys.stderr.write('It appears that Luci is running. Please stop Luci before attempting to backup your installation.\n')
  736.                         return -1
  737.                 else:
  738.                         sys.stderr.write('Unable to open the Luci database \"' + dbfn + '\":' + str(e) + '\n')
  739.                         return -1
  740.         except Exception, e:
  741.                 sys.stderr.write('Unable to open the Luci database \"' + dbfn + '\":' + str(e) + '\n')
  742.                 return -1
  743.  
  744.         try:
  745.                 sys.stderr = null
  746.                 tempuser = AccessControl.User.UnrestrictedUser('admin', '',
  747.                                         ('manage','Manager', 'Owner', 'View', 'Authenticated'), [])
  748.  
  749.                 newSecurityManager(None, tempuser)
  750.  
  751.                 app = conn.root()['Application']
  752.                 AppInitializer(app).initialize()
  753.                 sys.stderr = orig_stderr
  754.         except:
  755.                 sys.stderr = orig_stderr
  756.                 sys.stderr.write('An error occurred while initializing the Luci installation for restoration from backup\n')
  757.                 return -1
  758.  
  759.         app.luci.portal_memberdata.pruneMemberDataContents()
  760.         transaction.commit()
  761.  
  762.         try:
  763.                 acl_users = app.acl_users.users
  764.                 if not (acl_users and len(acl_users)):
  765.                         raise
  766.         except:
  767.                 sys.stderr.write('Your Luci installation appears to be corrupt.\n')
  768.                 return -1
  769.  
  770.         users = {}
  771.         systems = {}
  772.         clusters = {}
  773.  
  774.         try:
  775.                 acl_users = app.acl_users.users
  776.                 if len(acl_users) < 1:
  777.                         raise
  778.                 users['admin'] = {
  779.                         'id': 'admin',
  780.                         'name': 'admin',
  781.                         'passwd': app.acl_users.users._user_passwords['admin']
  782.                 }
  783.         except:
  784.                 sys.stderr.write('Unable to find the admin user.\n')
  785.                 return -1
  786.  
  787.         acl_users = app.luci.acl_users.source_users
  788.         if acl_users and len(acl_users):
  789.                 for i in app.luci.acl_users.source_users._user_passwords.items():
  790.                         try:
  791.                                 users[i[0]] = {
  792.                                         'id': i[0],
  793.                                         'name': i[0],
  794.                                         'passwd': i[1]
  795.                                 }
  796.                         except:
  797.                                 try:
  798.                                         sys.stderr.write('An error occurred while saving details for user \"' + i[0] + '\"\n')
  799.                                 except:
  800.                                         sys.stderr.write('An error occurred while saving user information.')
  801.                                 return -1
  802.  
  803.         try:
  804.                 membertool = getToolByName(app.luci, 'portal_membership')
  805.                 if not membertool:
  806.                         raise
  807.                 for mem in membertool.listMembers():
  808.                         try:
  809.                                 for i in [ 'login_time', 'last_login_time', 'must_change_password', 'email' ]:
  810.                                         prop = mem.getProperty(i)
  811.                                         if prop != '':
  812.                                                 users[mem.id][i] = str(prop)
  813.                         except:
  814.                                 continue
  815.         except:
  816.                 pass
  817.  
  818.         try:
  819.                 storagedir = app.luci.systems.storage
  820.                 clusterdir = app.luci.systems.cluster
  821.         except:
  822.                 sys.stderr.write('Your Luci installation appears to be corrupt.')
  823.                 return -1
  824.  
  825.         if storagedir and len(storagedir):
  826.                 for i in storagedir.objectItems():
  827.                         systems[i[0]] = { 'id': i[0] }
  828.                         if hasattr(i[1], 'title'):
  829.                                 systems[i[0]]['title'] = getattr(i[1], 'title')
  830.                         else:
  831.                                 systems[i[0]]['title'] = '__luci__:system'
  832.  
  833.                         if hasattr(i[1], '__ac_local_roles__'):
  834.                                 roles = getattr(i[1], '__ac_local_roles__')
  835.                                 if roles:
  836.                                         systems[i[0]]['permList'] = map(lambda x: x[0], filter(lambda x: len(x) > 1 and 'View' in x[1], roles.items()))
  837.                         else:
  838.                                 systems[i[0]]['permList'] = {}
  839.  
  840.         if clusterdir and len(clusterdir):
  841.                 for i in clusterdir.objectItems():
  842.                         cluster_name = i[0]
  843.                         clusters[cluster_name] = { 'id': cluster_name, 'csystemList': {} }
  844.                         if hasattr(i[1], 'title'):
  845.                                 clusters[cluster_name]['title'] = getattr(i[1], 'title')
  846.                         else:
  847.                                 clusters[cluster_name]['title'] = '__luci__:cluster'
  848.  
  849.                         if hasattr(i[1], '__ac_local_roles__'):
  850.                                 roles = getattr(i[1], '__ac_local_roles__')
  851.                                 if roles:
  852.                                         clusters[cluster_name]['permList'] = map(lambda x: x[0], filter(lambda x: len(x) > 1 and 'View' in x[1], roles.items()
  853. ))
  854.                         else:
  855.                                 clusters[cluster_name]['permList'] = {}
  856.  
  857.                         for csystem in i[1].objectItems():
  858.                                 csystem_hash = { 'id': csystem[0] }
  859.  
  860.                                 if hasattr(csystem[1], 'title'):
  861.                                         csystem_hash['title'] = getattr(csystem[1], 'title')
  862.                                 else:
  863.                                         csystem_hash['title'] = '__luci__:csystem:' + cluster_name
  864.                                 clusters[cluster_name]['csystemList'][csystem[0]] = csystem_hash
  865.  
  866.         transaction.commit()
  867.         conn.close()
  868.         db.pack()
  869.         db.close()
  870.         fs.close()
  871.  
  872.         backup_data = {
  873.                 'userList': users,
  874.                 'systemList': systems,
  875.                 'clusterList': clusters
  876.         }
  877.  
  878.         doc = xml.dom.minidom.Document()
  879.         luciData = doc.createElement('luci')
  880.         doc.appendChild(luciData)
  881.         dataNode = dataToXML(doc, backup_data, 'backupData')
  882.  
  883.         certList = doc.createElement('certificateList')
  884.         for i in ssl_key_data:
  885.                 try:
  886.                         certfile = file(i['id'], 'rb')
  887.                         output = certfile.read()
  888.                         certfile.close()
  889.  
  890.                         if len(output) < 1:
  891.                                 raise
  892.                 except:
  893.                         sys.stderr.write('Unable to read \"' + i['id'] + '\"\n')
  894.                         # An error backing up anything other than the config
  895.                         # is fatal.
  896.                         if i['type'] != 'config':
  897.                                 return None
  898.  
  899.                 certNode = doc.createElement('certificate')
  900.                 certNode.setAttribute('id', i['id'])
  901.                 certNode.setAttribute('name', i['name'])
  902.                 certNode.setAttribute('type', i['type'])
  903.                 certNode.setAttribute('mode', str(oct(i['mode'])))
  904.                 textNode = doc.createTextNode('\n' + output)
  905.                 certNode.appendChild(textNode)
  906.                 certList.appendChild(certNode)
  907.  
  908.         dataNode.appendChild(certList.cloneNode(True))
  909.         luciData.appendChild(dataNode)
  910.  
  911.         return doc
  912.  
  913.  
  914. def _execWithCaptureErrorStatus(command, argv, searchPath = 0, root = '/', stdin = 0, catchfd = 1, catcherrfd = 2, closefd = -1):
  915.     if not os.access (root + command, os.X_OK):
  916.         raise RuntimeError, '%s is not executable' % command
  917.  
  918.     (read, write) = os.pipe()
  919.     (read_err, write_err) = os.pipe()
  920.  
  921.     childpid = os.fork()
  922.     if (not childpid):
  923.         # child
  924.         if (root and root != '/'):
  925.                         os.chroot (root)
  926.         if isinstance(catchfd, tuple):
  927.             for fd in catchfd:
  928.                 os.dup2(write, fd)
  929.         else:
  930.             os.dup2(write, catchfd)
  931.         os.close(write)
  932.         os.close(read)
  933.  
  934.         if isinstance(catcherrfd, tuple):
  935.             for fd in catcherrfd:
  936.                 os.dup2(write_err, fd)
  937.         else:
  938.             os.dup2(write_err, catcherrfd)
  939.         os.close(write_err)
  940.         os.close(read_err)
  941.  
  942.         if closefd != -1:
  943.             os.close(closefd)
  944.  
  945.         if stdin:
  946.             os.dup2(stdin, 0)
  947.             os.close(stdin)
  948.  
  949.         if (searchPath):
  950.             os.execvp(command, argv)
  951.         else:
  952.             os.execv(command, argv)
  953.         # will never come here
  954.  
  955.     os.close(write)
  956.     os.close(write_err)
  957.  
  958.     rc = ""
  959.     rc_err = ""
  960.     in_list = [read, read_err]
  961.     while len(in_list) != 0:
  962.         i, o, e = select(in_list, [], [], 0.1)
  963.         for fd in i:
  964.             if fd == read:
  965.                 s = os.read(read, 1000)
  966.                 if s == '':
  967.                     in_list.remove(read)
  968.                 rc = rc + s
  969.             if fd == read_err:
  970.                 s = os.read(read_err, 1000)
  971.                 if s == '':
  972.                     in_list.remove(read_err)
  973.                 rc_err = rc_err + s
  974.  
  975.     os.close(read)
  976.     os.close(read_err)
  977.  
  978.     status = -1
  979.     try:
  980.         (pid, status) = os.waitpid(childpid, 0)
  981.     except OSError, (errno, msg):
  982.         sys.stderr.write(__name__ +  'waitpid: ' +  msg + '\n')
  983.  
  984.     if os.WIFEXITED(status):
  985.         status = os.WEXITSTATUS(status)
  986.     else:
  987.         status = -1
  988.  
  989.     return (rc, rc_err, status)
  990.  
  991.  
  992.  
  993.  
  994.  
  995.  
  996.  
  997. def luci_initialized():
  998.     # existence of privkey.pem file and
  999.     # admin password (not the one Data.fs comes with)
  1000.     # mean that luci has been initialized
  1001.     b1 = get_default_passwd_reset_flag()
  1002.     b2 = os.access(SSL_PRIVKEY_PATH, os.F_OK)
  1003.     return b1 and b2
  1004.  
  1005.  
  1006.  
  1007. def generate_ssl_certs():
  1008.     command = '/bin/rm'
  1009.     args = [command, '-f', SSL_PRIVKEY_PATH, SSL_PUBKEY_PATH]
  1010.     _execWithCaptureErrorStatus(command, args)
  1011.  
  1012.     # /usr/bin/openssl genrsa -out /var/lib/luci/var/certs/privkey.pem 2048 > /dev/null 2>&1
  1013.     command = '/usr/bin/openssl'
  1014.     args = [command, 'genrsa', '-out', SSL_PRIVKEY_PATH, '2048']
  1015.     _execWithCaptureErrorStatus(command, args)
  1016.  
  1017.     # /usr/bin/openssl req -new -x509 -key /var/lib/luci/var/certs/privkey.pem -out /var/lib/luci/var/certs/cacert.pem -days 1825 -config /var/lib/luci/var/ce
  1018. rts/cacert.config
  1019.     command = '/usr/bin/openssl'
  1020.     args = [command, 'req', '-new', '-x509', '-key', SSL_PRIVKEY_PATH, '-out', SSL_PUBKEY_PATH, '-days', '1825', '-config', SSL_KEYCONFIG_PATH]
  1021.     _execWithCaptureErrorStatus(command, args)
  1022.  
  1023.     # take ownership and restrict access
  1024.     try:
  1025.             uid, gid = get_luci_uid_gid()
  1026.             os.chown(SSL_PRIVKEY_PATH, uid, gid)
  1027.             os.chown(SSL_PUBKEY_PATH, uid, gid)
  1028.             os.chmod(SSL_PRIVKEY_PATH, 0600)
  1029.             os.chmod(SSL_PUBKEY_PATH, 0644)
  1030.     except:
  1031.             command = '/bin/rm'
  1032.             args = [command, '-f', SSL_PRIVKEY_PATH, SSL_PUBKEY_PATH]
  1033.             _execWithCaptureErrorStatus(command, args)
  1034.             return False
  1035.  
  1036.     return True
  1037.  
  1038.  
  1039. def restart_message():
  1040.     print
  1041.     print
  1042.     print 'Restart the Luci server for changes to take effect'
  1043.     print 'eg. service luci restart'
  1044.     print
  1045.     return
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051. def init(argv):
  1052.         if luci_initialized():
  1053.                 sys.stderr.write('Luci site has been already initialized.\n')
  1054.                 sys.stderr.write('If you want to reset admin password, execute\n')
  1055.                 sys.stderr.write('\t' + argv[0] + ' password\n')
  1056.                 sys.exit(1)
  1057.  
  1058.         print 'Initializing the Luci server\n'
  1059.  
  1060.         print '\nCreating the \'admin\' user\n'
  1061.         new_password = read_passwd('Enter password: ', 'Confirm password: ')
  1062.         print '\nPlease wait...'
  1063.         if not set_zope_passwd('admin', new_password):
  1064.                 restore_luci_db_fsattr()
  1065.                 print 'The admin password has been successfully set.'
  1066.         else:
  1067.                 sys.stderr.write('Unable to set the admin user\'s password.\n')
  1068.                 sys.exit(1)
  1069.  
  1070.         print 'Generating SSL certificates...'
  1071.         if generate_ssl_certs() == False:
  1072.                 sys.stderr.write('failed. exiting ...\n')
  1073.                 sys.exit(1)
  1074.  
  1075.         print 'Luci server has been successfully initialized'
  1076.         restart_message()
  1077.  
  1078.         return
  1079.  
  1080.  
  1081. def password(argv):
  1082.         passwd = None
  1083.         if '--random' in argv:
  1084.                 print 'Resetting the admin user\'s password to some random value\n'
  1085.                 try:
  1086.                         rand = open('/dev/urandom', 'r')
  1087.                         passwd = rand.read(16)
  1088.                         rand.close()
  1089.                 except:
  1090.                         sys.stderr.write('Unable to read from /dev/urandom\n')
  1091.                         sys.exit(1)
  1092.         else:
  1093.                 if not luci_initialized():
  1094.                         sys.stderr.write('The Luci site has not been initialized.\n')
  1095.                         sys.stderr.write('To initialize it, execute\n')
  1096.                         sys.stderr.write('\t' + argv[0] + ' init\n')
  1097.                         sys.exit(1)
  1098.  
  1099.                 print 'Resetting the admin user\'s password\n'
  1100.                 passwd = read_passwd('Enter new password: ', 'Confirm password: ')
  1101.  
  1102.         print '\nPlease wait...'
  1103.         if not set_zope_passwd('admin', passwd):
  1104.                 print 'The admin password has been successfully reset.'
  1105.         else:
  1106.                 sys.stderr.write('Unable to set the admin user\'s password.\n')
  1107.                 sys.exit(1)
  1108.  
  1109.         restart_message()
  1110.  
  1111.         return
  1112.  
  1113.  
  1114. def backup(argv):
  1115.         # If the site hasn't been initialized, there's nothing to
  1116.         # save, and luci_backup() will fail
  1117.         if not luci_initialized():
  1118.                 print 'The Luci site has not been initialized\n'
  1119.                 print 'Nothing to backup\n'
  1120.                 sys.exit(0)
  1121.  
  1122.         print 'Backing up the Luci server...'
  1123.  
  1124.         try:
  1125.                 os.umask(077)
  1126.         except: pass
  1127.  
  1128.         doc = luci_backup(argv[2:])
  1129.         restore_luci_db_fsattr()
  1130.         if doc == -1:
  1131.                 sys.stderr.write('The Luci backup failed. Exiting.\n')
  1132.                 sys.exit(1)
  1133.  
  1134.         try:
  1135.                 # The LUCI_BACKUP_DIR must not be world-writable
  1136.                 # as the code below is obviously not safe against
  1137.                 # races.
  1138.                 os.stat(LUCI_BACKUP_PATH)
  1139.                 trynum = 1
  1140.                 basename = '/luci_backup-'
  1141.  
  1142.                 while True:
  1143.                         oldbackup = LUCI_BACKUP_DIR + basename + str(trynum) + '.xml'
  1144.                         if not os.path.exists(oldbackup):
  1145.                                 try:
  1146.                                         os.rename(LUCI_BACKUP_PATH, oldbackup)
  1147.                                 except:
  1148.                                         sys.stderr.write('Unable to rename the existing backup file.\n')
  1149.                                         sys.stderr.write('The Luci backup failed.\n')
  1150.                                 break
  1151.                         trynum += 1
  1152.         except OSError, e:
  1153.                 #if e[0] == 2:
  1154.                 pass
  1155.  
  1156.         try:
  1157.                 f = file(LUCI_BACKUP_PATH, 'wb+')
  1158.         except:
  1159.                 sys.stderr.write('Unable to open \"' + LUCI_BACKUP_PATH + '\" to write backup.\n')
  1160.                 sys.stderr.write('The Luci backup failed.\n')
  1161.                 sys.exit(1)
  1162.  
  1163.         try:
  1164.                 os.chmod(LUCI_BACKUP_PATH, 0600)
  1165.         except OSError, e:
  1166.                 sys.stderr.write('An error occurred while making \"' + LUCI_BACKUP_PATH + '\" read-only: '  + e + '\n')
  1167.                 sys.stderr.write('Please check that this file is not world-readable.\n')
  1168.  
  1169.         try:
  1170.                 f.write(doc.toprettyxml())
  1171.                 f.close()
  1172.         except:
  1173.                 sys.stderr.write('The Luci backup failed.\n')
  1174.                 sys.exit(1)
  1175.  
  1176.         print 'Luci backup was successful.\nThe backup data is contained in the file \"' + LUCI_BACKUP_PATH + '\"'
  1177.  
  1178.  
  1179. def restore(argv):
  1180.         print 'Restoring the Luci server...'
  1181.  
  1182.         try:
  1183.                 os.umask(077)
  1184.         except:
  1185.                 pass
  1186.  
  1187.         if luci_restore(argv[2:]):
  1188.                 ret = False
  1189.                 sys.stderr.write('The Luci restore failed. Try reinstalling Luci, then restoring again.\n')
  1190.         else:
  1191.                 set_default_passwd_reset_flag()
  1192.                 ret = True
  1193.                 print 'Restore was successful.'
  1194.                 restart_message()
  1195.  
  1196.         if restore_luci_db_fsattr():
  1197.                 return False
  1198.  
  1199.         return ret
  1200.  
  1201.  
  1202. def luci_help(argv):
  1203.     print 'Usage:'
  1204.     print argv[0] + ' [init|backup|restore|password|help]'
  1205.     print
  1206.     print '\tinit: initialize Luci site'
  1207.     print '\tpassword: reset admin password'
  1208.     print '\t\t--random: reset admin password to random value (disable account)'
  1209.     print '\tbackup: backup Luci site to a file'
  1210.     print '\trestore: restore Luci site from backup'
  1211.     print '\thelp: this help message'
  1212.     print
  1213.  
  1214.  
  1215.  
  1216. def test_luci_installation():
  1217.    # perform basic checks
  1218.    # TODO: do more tests
  1219.  
  1220.    # check if luci user and group are present on the system
  1221.    try:
  1222.            get_luci_uid_gid()
  1223.    except:
  1224.            sys.stderr.write('There is a problem with luci installation!\n')
  1225.            sys.stderr.write('Mising luci\'s system account and group')
  1226.            sys.stderr.write('Recommended action: reinstall luci\n\n')
  1227.            sys.exit(3)
  1228.  
  1229.    return True
  1230.  
  1231.  
  1232. def main(argv):
  1233.     if len(argv) < 2:
  1234.         luci_help(argv)
  1235.         sys.exit(1)
  1236.  
  1237.     test_luci_installation()
  1238.  
  1239.     if 'init' in argv:
  1240.         init(argv)
  1241.     elif 'backup' in argv:
  1242.         backup(argv)
  1243.     elif 'restore' in argv:
  1244.         restore(argv)
  1245.     elif 'password' in argv:
  1246.         password(argv)
  1247.     elif 'help' in argv:
  1248.         luci_help(argv)
  1249.     else:
  1250.         sys.stderr.write('Unknown command\n\n')
  1251.         luci_help(argv)
  1252.         sys.exit(1)
  1253.  
  1254.  
  1255. # If called from the command line
  1256. if __name__ == '__main__':
  1257.     main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement