def POST(self): global error_msg if not been_through_subconfig: self.logger.info('tried Net POST....back to /su') raise web.seeother('/su') self.logger.debug('in Net POST') save_last_get('Net POST') form = web.input() error_msg = '' outdata = [] for f in ['Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID', 'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name', 'Station Port', 'External Station Port', 'Remote Substation Access Port', 'Extender SSID', 'Extender Password']: if f in form: form[f] = form[f].strip() # use hidden SSID if provided using_hidden_ssid = False if 'Hidden SSID' in form and form['Hidden SSID'] != '': using_hidden_ssid = True form['SSID'] = form['Hidden SSID'] self.logger.info('using Hidden SSID') use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet' if gv.sd['remote_radio_substation']: form['SSID'] = 'using radio' net = 'radio' elif not use_eth0: net = 'wlan0' else: form['SSID'] = 'using eth0' net = 'eth0' self.logger.debug('in Net POST: ' + form['SSID']) gv.sd['light_ip'] = 1 try: if form['DNS Nameservers'][0:1] == 'X' and \ (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '): gv.sd['light_ip'] = 0 # hack to disable blinking led on startup with leading X in nameservers form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip() except: pass if not gv.sd['remote_radio_substation'] and 'Use DHCP' in form: for d in ['DNS Search', 'DNS Nameservers']: if d in form and form[d] != '': error_msg = 'Error: "' + d + '" must be blank with "Use DHCP".' raise web.seeother('/cn') # back to form pass_len = 0 if 'Extender Password' not in form else len(form['Extender Password']) if 'Extender SSID' in form and form['Extender SSID'] != '': if pass_len < 8 or pass_len > 63: error_msg = 'Error: "Extender Password" must be between 8 and 63 characters.' raise web.seeother('/cn') # back to form else: # force data to be present and safe form['Extender SSID'] = '' form['Extender Password'] = '' pass_len = 0 if 'Password' not in form else len(form['Password']) if not gv.sd['remote_radio_substation'] and not using_eth0 and (pass_len < 8 or pass_len > 63): error_msg = 'Error: "Password" must be between 8 and 63 characters.' raise web.seeother('/cn') # back to form if 'Station Name' in form: sn = validate_fqdn(form['Station Name']) if sn == 'Irricloud': # error condition error_msg = 'Error: "Station Name" must have only letter and numbers.' raise web.seeother('/cn') # back to form elif len(sn) > 50 or len(sn) < 1: error_msg = 'Error: "Station Name" must be at most 50 characters.' raise web.seeother('/cn') # back to form form['Station Name'] = sn for portn in ['Station Port', 'External Station Port', 'Remote Substation Access Port', 'UPnP Refresh Rate']: if portn in form: try: port = int(form[portn]) except: error_msg = 'Error: "' + portn + '" must be integer.' raise web.seeother('/cn') # back to form if port < 0 or port > 65535: error_msg = 'Error: "' + portn + '" must be between 0 and 65535.' raise web.seeother('/cn') # back to form if portn == 'Station Port' and port == 9080: # specially reserved for proxy error_msg = 'Error: "' + portn + '" cannot be 9080.' raise web.seeother('/cn') # back to form try: drop = 0 with open('/etc/network/interfaces','r') as infile: iface = infile.readlines() for line in iface: if 'dns-nameservers' in line: continue # delete any old dns stuff did_iface_wlan0 = False if drop > 0: drop -= 1 continue if 'iface ' + net + ' inet' in line: if net == 'wlan0': did_iface_wlan0 = True if 'Use DHCP' in form: self.logger.info('Using dhcp: ' + form['SSID']) if 'static' in line: drop = 3 line = 'iface ' + net + ' inet manual\n' else: self.logger.info('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway']) if 'static' in line: drop = 3 outdata.append('iface ' + net + ' inet static\n') outdata.append(' address ' + form['Static IP'] + '\n') outdata.append(' netmask ' + form['Netmask'] + '\n') line = ' gateway ' + form['Gateway'] +'\n' outdata.append(line) if 'DNS Nameservers' in form and form['DNS Nameservers'] != '': line = ' dns-nameservers ' + form['DNS Nameservers'] +'\n' else: # use gateway line = ' dns-nameservers ' + form['Gateway'] +'\n' elif 'iface ' + 'wlan0' + ' inet' in line: # using eth0 or radio only, but need to clean up 10.0.0.1 entry if 'static' in line: drop = 3 line = 'iface ' + 'wlan0' + ' inet manual\n' did_iface_wlan0 = True outdata.append(line) if did_iface_wlan0: outdata.append(' wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n') except Exception as ex: self.logger.exception('Unexpected exception trying to configure network: ' + str(ex)) raise web.seeother('/cn') if len(outdata) == 0: self.logger.error('Expected data in /etc/network/interfaces') raise web.seeother('/cn') self.logger.info('stopping daemons before updating network interfaces') stop_daemons() try: with open('/etc/network/interfaces','w') as outfile: outfile.writelines(outdata) # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config if 'Use DHCP' in form: shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf') else: shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf') # if we are going to broadcast our own ssid to extend reach, save ssid and password broad_wpa_info = wpa_passphrase(form['Extender SSID'], form['Extender Password']) if len(broad_wpa_info['ssid']) > 2 and broad_wpa_info['ssid'][0] == '"': # strip off quotes for hostapd.conf broad_wpa_info['ssid'] = broad_wpa_info['ssid'][1:len(broad_wpa_info['ssid'])-1] gv.sd['extender_ssid'] = broad_wpa_info['ssid'] gv.sd['extender_psk'] = broad_wpa_info['psk'] if not gv.sd['remote_radio_substation'] and not use_eth0: wpa_supp_lines = ['ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'] wpa_supp_lines.append('update_config=1\n\n') if form['SSID'] != '' and form['Password'] != '': wpa_info = wpa_passphrase(form['SSID'], form['Password']) wpa_supp_lines.append('network={\n') wpa_supp_lines.append('\tssid=' + wpa_info['ssid'] + '\n') if using_hidden_ssid: wpa_supp_lines.append('\tscan_ssid=1\n') wpa_supp_lines.append('\tpsk=' + wpa_info['psk'] + '\n') wpa_supp_lines.append('}\n') else: self.logger.warning('missing ssid or password') with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile: outfile.writelines(wpa_supp_lines) # check if network connection was made # self.logger.debug('wpa_action stopping wlan0') # rc = subprocess.call(['wpa_action', 'wlan0', 'stop']) # self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc)) # time.sleep(1) # self.logger.debug('ifup wlan0') # rc = subprocess.call(['ifup', 'wlan0']) # self.logger.debug( 'ifup return: ' + str(rc)) # time.sleep(1) # rc = subprocess.call(['wpa_action', 'wlan0', 'reload']) # self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc)) # time.sleep(1) # reset_networking() if True or 'Do not validate network connection' in form or network_up(net, self.logger): #successful network connection. Finalize # copy the current versions to the save version cur_ip = get_ip(net) self.logger.info('success...cur_ip: ' + cur_ip) if gv.sd['enable_upnp']: # was enabled? Then cleanup. If network still points to 10.0.0.1 network cant cleanup! deletes = [] if gv.sd['external_htp'] != 0: deletes.append(gv.sd['external_htp']) if gv.sd['remote_support_port'] != 0: deletes.append(gv.sd['remote_support_port']) if gv.sd['external_proxy_port'] != 0: deletes.append(gv.sd['external_proxy_port']) update_upnp(cur_ip, self.logger, deletes) gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0 if gv.sd['enable_upnp']: if 'UPnP Refresh Rate' in form: gv.sd['upnp_refresh_rate'] = int(form['UPnP Refresh Rate']) if 'Station Name' in form: gv.sd['name'] = form['Station Name'] update_hostname(gv.sd['name']) if 'Station Port' in form: gv.sd['htp'] = int(form['Station Port']) if gv.sd['master']: gv.sd['master_ip'] = 'localhost' # update local master_port gv.sd['master_port'] == gv.sd['htp'] else: gv.sd['master_port'] = 0 gv.sd['external_htp'] = int(form['External Station Port']) if 'External Station Port' in form else 0 gv.sd['external_proxy_port'] = int(form['Remote Substation Access Port']) if 'Remote Substation Access Port' in form else 0 jsave(gv.sd, 'sd') self.logger.info('success....copying back interfaces and wpa') try: os.remove('/etc/resolv.conf') except: pass shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save') shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save') # self.logger.info('success....enabling sip') # subprocess.call(['systemctl', 'enable', 'sip.service']) ## subprocess.call(['update-rc.d', 'sip', 'enable']) ## subprocess.call(['update-rc.d', 'sip', 'defaults']) ## self.logger.info('disabling sip_net_finish') # subprocess.call(['systemctl', 'disable', 'sip_net_finish.service']) ## subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove']) # light_ip(cur_ip) self.logger.info('rebooting') subprocess.call(['reboot', '-h']) exit(0) else: raise Exception('Network Inaccessible') except Exception as ex: self.logger.exception('failed: ' + str(ex)) # restore saved /etc/network/interfaces and wpa_suplicant.conf self.logger.info('restore network files and exit. Exception: ' + str(ex)) shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces') shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf') exit(1) self.logger.error('sip_net_config: should have exited above. sip_monitor will restart') raise web.seeother('/cn')
def POST(self): global error_msg if not been_through_subconfig: self.logger.info('tried Net POST....back to /su') raise web.seeother('/su') self.logger.debug('in Net POST') save_last_get('Net POST') form = web.input() error_msg = '' outdata = [] for f in [ 'Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID', 'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name', 'Station Port', 'External Station Port', 'Remote Substation Access Port' ]: if f in form: form[f] = form[f].strip() # use hidden SSID if provided using_hidden_ssid = False if 'Hidden SSID' in form and form['Hidden SSID'] != '': using_hidden_ssid = True form['SSID'] = form['Hidden SSID'] self.logger.info('using Hidden SSID') use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet' if not use_eth0: net = 'wlan0' else: form['SSID'] = 'using eth0' net = 'eth0' self.logger.debug('in Net POST: ' + form['SSID']) gv.sd['light_ip'] = 1 try: if form['DNS Nameservers'][0:1] == 'X' and \ (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '): gv.sd[ 'light_ip'] = 0 # hack to disable blinking led on startup with leading X in nameservers form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip() except: pass if 'Use DHCP' in form: for d in ['DNS Search', 'DNS Nameservers']: if d in form and form[d] != '': error_msg = 'Error: "' + d + '" must be blank with "Use DHCP".' raise web.seeother('/cn') # back to form if 'Station Name' in form: sn = validate_fqdn(form['Station Name']) if sn == 'Irricloud': # error condition error_msg = 'Error: "Station Name" must have only letter and numbers.' raise web.seeother('/cn') # back to form elif len(sn) > 50 or len(sn) < 1: error_msg = 'Error: "Station Name" must be at most 50 characters.' raise web.seeother('/cn') # back to form form['Station Name'] = sn try: drop = 0 with open('/etc/network/interfaces', 'r') as infile: iface = infile.readlines() for line in iface: if 'dns-nameservers' in line: continue # delete any old dns stuff did_iface_wlan0 = False if drop > 0: drop -= 1 continue if 'iface ' + net + ' inet' in line: if net == 'wlan0': did_iface_wlan0 = True if 'Use DHCP' in form: self.logger.info('Using dhcp: ' + form['SSID']) if 'static' in line: drop = 3 line = 'iface ' + net + ' inet manual\n' else: self.logger.info('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway']) if 'static' in line: drop = 3 outdata.append('iface ' + net + ' inet static\n') outdata.append(' address ' + form['Static IP'] + '\n') outdata.append(' netmask ' + form['Netmask'] + '\n') line = ' gateway ' + form['Gateway'] + '\n' outdata.append(line) if 'DNS Nameservers' in form and form[ 'DNS Nameservers'] != '': line = ' dns-nameservers ' + form[ 'DNS Nameservers'] + '\n' else: # use gateway line = ' dns-nameservers ' + form[ 'Gateway'] + '\n' elif 'iface ' + 'wlan0' + ' inet' in line: # using eth0 but need to clean up 10.0.0.1 entry if 'static' in line: drop = 3 line = 'iface ' + 'wlan0' + ' inet manual\n' did_iface_wlan0 = True outdata.append(line) if did_iface_wlan0: outdata.append( ' wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n' ) except Exception as ex: self.logger.exception( 'Unexpected exception trying to configure network: ' + str(ex)) raise web.seeother('/cn') if len(outdata) == 0: self.logger.error('Expected data in /etc/network/interfaces') raise web.seeother('/cn') for portn in [ 'Station Port', 'External Station Port', 'Remote Substation Access Port', 'UPnP Refresh Rate' ]: if portn in form: try: port = int(form[portn]) except: error_msg = 'Error: "' + portn + '" must be integer.' raise web.seeother('/cn') # back to form if port < 0 or port > 65535: error_msg = 'Error: "' + portn + '" must be between 0 and 65535.' raise web.seeother('/cn') # back to form if portn == 'Station Port' and port == 9080: # specially reserved for proxy error_msg = 'Error: "' + portn + '" cannot be 9080.' raise web.seeother('/cn') # back to form self.logger.info('stopping daemons before updating network interfaces') if not use_eth0: stop_daemons() else: stop_daemons() try: with open('/etc/network/interfaces', 'w') as outfile: outfile.writelines(outdata) # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config if 'Use DHCP' in form: shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf') else: shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf') if not use_eth0: wpa_supp_lines = [ 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n' ] wpa_supp_lines.append('update_config=1\n\n') if form['SSID'] != '' and form['Password'] != '': # wpa_passphrase cannot handle blanks so quote strings ssid = form['SSID'].replace('"', '\"') passw = form['Password'].replace('"', '\"') cmd = '/usr/bin/wpa_passphrase "' + ssid + '" "' + passw + '" > passphrase' subprocess.call(cmd, shell=True) with open('passphrase', 'r') as f: pl = f.readlines() for line in pl: if '#psk=' in line: # drop cleartext password continue wpa_supp_lines.append(line) if using_hidden_ssid and 'ssid' in line: wpa_supp_lines.append('\tscan_ssid=1\n') subprocess.call(['rm', 'passphrase']) else: self.logger.warning('missing ssid or password') with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile: outfile.writelines(wpa_supp_lines) # check if network connection was made # self.logger.debug('wpa_action stopping wlan0') # rc = subprocess.call(['wpa_action', 'wlan0', 'stop']) # self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc)) # time.sleep(1) # self.logger.debug('ifup wlan0') # rc = subprocess.call(['ifup', 'wlan0']) # self.logger.debug( 'ifup return: ' + str(rc)) # time.sleep(1) # rc = subprocess.call(['wpa_action', 'wlan0', 'reload']) # self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc)) # time.sleep(1) # reset_networking() if True or 'Do not validate network connection' in form or network_up( net, self.logger): #successful network connection. Finalize # copy the current versions to the save version cur_ip = get_ip(net) self.logger.info('success...cur_ip: ' + cur_ip) if gv.sd[ 'enable_upnp']: # was enabled? Then cleanup. If network still points to 10.0.0.1 network cant cleanup! deletes = [] if gv.sd['external_htp'] != 0: deletes.append(gv.sd['external_htp']) if gv.sd['remote_support_port'] != 0: deletes.append(gv.sd['remote_support_port']) if gv.sd['external_proxy_port'] != 0: deletes.append(gv.sd['external_proxy_port']) update_upnp(cur_ip, self.logger, deletes) gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0 if gv.sd['enable_upnp']: if 'UPnP Refresh Rate' in form: gv.sd['upnp_refresh_rate'] = int( form['UPnP Refresh Rate']) if 'Station Name' in form: gv.sd['name'] = form['Station Name'] update_hostname(gv.sd['name']) if 'Station Port' in form: gv.sd['htp'] = int(form['Station Port']) if gv.sd['master']: gv.sd[ 'master_ip'] = 'localhost' # update local master_port gv.sd['master_port'] == gv.sd['htp'] else: gv.sd['master_port'] = 0 gv.sd['external_htp'] = int( form['External Station Port'] ) if 'External Station Port' in form else 0 gv.sd['external_proxy_port'] = int( form['Remote Substation Access Port'] ) if 'Remote Substation Access Port' in form else 0 jsave(gv.sd, 'sd') self.logger.info('success....copying back interfaces and wpa') try: os.remove('/etc/resolv.conf') except: pass shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save') shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save') # self.logger.info('success....enabling sip') # subprocess.call(['systemctl', 'enable', 'sip.service']) ## subprocess.call(['update-rc.d', 'sip', 'enable']) ## subprocess.call(['update-rc.d', 'sip', 'defaults']) ## self.logger.info('disabling sip_net_finish') # subprocess.call(['systemctl', 'disable', 'sip_net_finish.service']) ## subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove']) # light_ip(cur_ip) self.logger.info('rebooting') subprocess.call(['reboot', '-h']) exit(0) else: raise Exception('Network Inaccessible') except Exception as ex: self.logger.exception('failed: ' + str(ex)) # restore saved /etc/network/interfaces and wpa_suplicant.conf self.logger.info('restore network files and exit. Exception: ' + str(ex)) shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces') shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf') exit(1) self.logger.error( 'sip_net_config: should have exited above. sip_monitor will restart' ) raise web.seeother('/cn')
def run(self): if disable_substations: return gv.logger.info('Substation plugin started') time.sleep(7) # let things wake up, but keep less than delay for sending email last_message_base = gv.now - 60 last_day = gv.now//86400 # wait at least a day before removing stale log files so startup does not delete them while True: try: cur_day = gv.now//86400 if gv.sd['slave'] and gv.now - last_message_base >= 60: try: last_message_base = gv.now data = message_base('suslj') if 'unreachable' in data: raise IOError, 'UnreachableMaster' force_reboot = False # update common data that has changed on the master for grouping in data: if gv.sd['master']: continue for key in data[grouping]: if grouping == 'sd': if key in gv.sd: if gv.sd[key] != data['sd'][key]: gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key])) if key == 'remote_support_port' and gv.sd['enable_upnp']: gv.logger.critical('substation_run: Unexpected key of remote_support_port') if gv.sd[key] != 0: # delete old update_upnp(get_ip(), [gv.sd[key]]) if data['sd'][key] != 0: update_upnp(get_ip(), [], [[22, data['sd'][key]]]) gv.sd[key] = data['sd'][key] if key == 'tza': with open('/etc/timezone','w') as file: file.write(qdict['o'+f]+'\n') subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata']) force_reboot = True elif key == 'loc' or key == 'lang': force_reboot = True else: gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key])) gv.sd[key] = data['sd'][key] elif grouping in gv.plugin_data: if key in gv.plugin_data[grouping]: if gv.plugin_data[grouping][key] != data[grouping][key]: gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key])) gv.plugin_data[grouping][key] = data[grouping][key] else: gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key])) gv.plugin_data[grouping][key] = data[grouping][key] elif grouping == 'other': if key == 'websession': web.config._session.user = data[grouping][key] elif key == 'datetime': try: pass # subprocess.call(['date', '--set='+data[grouping][key]]) except: gv.logger.exception('Could not set datetime to ' + data[grouping][key]) if grouping == 'sd': jsave(gv.sd, 'sd') elif grouping != 'other': pass if force_reboot: reboot(5) # give a few seconds before reboot except Exception as ex: gv.logger.info('No master response. ip: ' + get_ip_to_base() + \ ' port: ' + str(gv.sd['master_port']) + \ ' Exception: ' + str(ex)) try: iwout = subprocess.check_output(['iwconfig', 'wlan0']) lines = iwout.split('\n') for l in lines: if 'ESSID:' in l: gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):]) except Exception as ex: gv.logger.info('slave could not check iwconfig: ' + str(ex)) if gv.sd['master']: for subid in range(1,len(gv.plugin_data['su']['subinfo'])): sub = gv.plugin_data['su']['subinfo'][subid] try: if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out qd = {'substation':subid} load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive except Exception as ex: gv.logger.info('substations reach out to slave: No response from slave: ' + sub['name'] + ' Exception: ' + str(ex)) sub['status'] = 'unreachable' try: iwout = subprocess.check_output(['iwconfig', 'wlan0']) lines = iwout.split('\n') for l in lines: if 'ESSID:' in l: gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):]) except Exception as ex: gv.logger.info('master could not check iwconfig: ' + str(ex)) if cur_day != last_day: last_day = cur_day # delete any imported log files from substations that are no longer active files = glob.glob('./data/imported_logs/*') for full_name in files: sub_name = full_name[full_name.rfind('/')+1:] found_slave = 0 for subid in range(1,len(gv.plugin_data['su']['subinfo'])): if sub_name == gv.plugin_data['su']['subinfo'][subid]['name']: found_slave = subid break if found_slave == 0: try: shutil.rmtree(full_name) gv.logger.info('removed substree: ' + full_name) except Exception as ex: gv.logger.warning('failed to remove substree: ' + full_name + ' ex: ' + str(ex)) except Exception as ex: self.start_status('', 'Substation encountered error: ' + str(ex)) self._sleep(30)
def POST(self): self.logger.debug('in Net POST') save_last_get('Net POST') form = web.input() outdata = [] net = 'eth0' if 'Use Hardwired eth0' in form else 'wlan0' # use hidden SSID if provided using_hidden_ssid = False if 'Hidden SSID' in form and form['Hidden SSID'].strip() != '': using_hidden_ssid = True form['SSID'] = form['Hidden SSID'] self.logger.info('using Hidden SSID') use_eth0 = 'SSID' not in form if not use_eth0: form['SSID'] = form['SSID'].strip() form['Password'] = form['Password'].strip() else: form['SSID'] = 'using eth0' self.logger.debug('in Net POST: ' + form['SSID']) try: drop = 0 with open('/etc/network/interfaces','r') as infile: iface = infile.readlines() for line in iface: did_iface_wlan0 = False if drop > 0: drop -= 1 continue if 'iface ' + net + ' inet' in line: if net == 'wlan0': did_iface_wlan0 = True if 'Use DHCP' in form: self.logger.debug('Using dhcp: ' + form['SSID']) if 'static' in line: drop = 3 line = 'iface ' + net + ' inet manual\n' else: self.logger.debug('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway']) if 'static' in line: drop = 3 outdata.append('iface ' + net + ' inet static\n') outdata.append(' address ' + form['Static IP'] + '\n') outdata.append(' netmask ' + form['Netmask'] + '\n') line = ' gateway ' + form['Gateway'] +'\n' outdata.append(line) if did_iface_wlan0: outdata.append(' wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n') except Exception as ex: self.logger.exception('Unexpected exception trying to configure network: ' + str(ex)) raise web.seeother('/cn') if len(outdata) == 0: self.logger.error('Expected data in /etc/network/interfaces') raise web.seeother('/cn') self.logger.debug('stopping daemons before updating network interfaces') # if not use_eth0: # stop_daemons() try: with open('/etc/network/interfaces','w') as outfile: outfile.writelines(outdata) if not use_eth0: wpa_supp_lines = ['ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'] wpa_supp_lines.append('update_config=1\n\n') if form['SSID'] != '' and form['Password'] != '': # wpa_passphrase cannot handle blanks cmd = 'wpa_passphrase ' + form['SSID'] + ' ' + form['Password'] + ' > passphrase' subprocess.call(cmd, shell=True) with open('passphrase', 'r') as f: pl = f.readlines() for line in pl: wpa_supp_lines.append(line) if using_hidden_ssid and 'ssid' in line: wpa_supp_lines.append('\tscan_ssid=1\n') subprocess.call(['rm', 'passphrase']) else: self.logger.warning('missing ssid or password') with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile: outfile.writelines(wpa_supp_lines) # check if network connection was made self.logger.debug('wpa_action stopping wlan0') rc = subprocess.call(['wpa_action', 'wlan0', 'stop']) self.logger.debug( 'wpa_action return: ' + str(rc)) time.sleep(1) self.logger.debug('ifup wlan0') rc = subprocess.call(['ifup', net]) self.logger.debug( 'ifup return: ' + str(rc)) time.sleep(2) if network_up(net): #successful network connection. Finalize # copy the current versions to the save version if gv.sd['enable_upnp']: # was enabled? Then cleanup cur_ip = get_ip(net) deletes = [] if gv.sd['external_htp'] != 0: deletes.append(gv.sd['external_htp']) if gv.sd['remote_support_port'] != 0: deletes.append(gv.sd['remote_support_port']) update_upnp(cur_ip, deletes) gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0 if gv.sd['enable_upnp']: if 'UPnP Refresh Rate' in form: gv.sd['upnp_refresh_rate'] = int(form['UPnP Refresh Rate']) if 'System Name' in form: gv.sd['name'] = form['System Name'] jsave(gv.sd, 'sd') if 'System Port' in form: gv.sd['htp'] = int(form['System Port']) jsave(gv.sd, 'sd') if 'External System Port' in form: gv.sd['external_htp'] = int(form['External System Port']) self.logger.info('success....copying back interfaces and wpa') shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save') shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save') # self.logger.info('success....enabling boiler') # subprocess.call(['update-rc.d', 'boiler', 'defaults']) # self.logger.info('disabling boiler_net_finish') # subprocess.call(['update-rc.d', 'boiler_net_finish', 'remove']) self.logger.info('rebooting') subprocess.call(['reboot', '-h']) exit(0) else: raise Exception('Network Inaccessible') except Exception as ex: self.logger.exception('failed: ' + str(ex)) # restore saved /etc/network/interfaces and wpa_suplicant.conf self.logger.info('restore network files and exit. Exception: ' + str(ex)) shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces') shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf') exit(1) self.logger.error('boiler_net_config: should have exited above. boiler_monitor will restart') raise web.seeother('/')
def run(self): if disable_substations: return gv.logger.info('Substation plugin started') time.sleep(7) # let things wake up, but keep less than delay for sending email last_message_base = gv.now - 60 while True: try: if gv.sd['slave'] and gv.now - last_message_base >= 60: try: last_message_base = gv.now data = message_base('suslj') if 'unreachable' in data: raise IOError, 'UnreachableMaster' force_reboot = False # update common data that has changed on the master for grouping in data: if gv.sd['master']: continue for key in data[grouping]: if grouping == 'sd': if key in gv.sd: if gv.sd[key] != data['sd'][key]: gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key])) if key == 'remote_support_port' and gv.sd['enable_upnp']: gv.logger.critical('substation_run: Unexpected key of remote_support_port') if gv.sd[key] != 0: # delete old update_upnp(get_ip(), [gv.sd[key]]) if data['sd'][key] != 0: update_upnp(get_ip(), [], [[22, data['sd'][key]]]) gv.sd[key] = data['sd'][key] if key == 'tza': with open('/etc/timezone','w') as file: file.write(qdict['o'+f]+'\n') subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata']) force_reboot = True elif key == 'loc' or key == 'lang': force_reboot = True else: gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key])) gv.sd[key] = data['sd'][key] elif grouping in gv.plugin_data: if key in gv.plugin_data[grouping]: if gv.plugin_data[grouping][key] != data[grouping][key]: gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key])) gv.plugin_data[grouping][key] = data[grouping][key] else: gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key])) gv.plugin_data[grouping][key] = data[grouping][key] elif grouping == 'other': if key == 'websession': web.config._session.user = data[grouping][key] elif key == 'datetime': try: pass # subprocess.call(['date', '--set='+data[grouping][key]]) except: gv.logger.exception('Could not set datetime to ' + data[grouping][key]) if grouping == 'sd': jsave(gv.sd, 'sd') elif grouping != 'other': pass if force_reboot: reboot(5) # give a few seconds before reboot except Exception as ex: gv.logger.info('No master response. ip: ' + get_ip_to_base() + \ ' port: ' + str(gv.sd['master_port']) + \ ' Exception: ' + str(ex)) try: iwout = subprocess.check_output(['iwconfig', 'wlan0']) lines = iwout.split('\n') for l in lines: if 'ESSID:' in l: gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):]) except Exception as ex: gv.logger.info('slave could not check iwconfig: ' + str(ex)) if gv.sd['master']: for subid in range(1,len(gv.plugin_data['su']['subinfo'])): sub = gv.plugin_data['su']['subinfo'][subid] try: if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out qd = {'substation':subid} load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive except Exception as ex: gv.logger.info('substations reach out to slave: No response from slave: ' + sub['name'] + ' Exception: ' + str(ex)) sub['status'] = 'unreachable' try: iwout = subprocess.check_output(['iwconfig', 'wlan0']) lines = iwout.split('\n') for l in lines: if 'ESSID:' in l: gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):]) except Exception as ex: gv.logger.info('master could not check iwconfig: ' + str(ex)) except Exception as ex: self.start_status('', 'Substation encountered error: ' + str(ex)) self._sleep(30)
def POST(self): self.logger.debug('in Net POST') save_last_get('Net POST') form = web.input() outdata = [] net = 'eth0' if 'Use Hardwired eth0' in form else 'wlan0' # use hidden SSID if provided using_hidden_ssid = False if 'Hidden SSID' in form and form['Hidden SSID'].strip() != '': using_hidden_ssid = True form['SSID'] = form['Hidden SSID'] self.logger.info('using Hidden SSID') use_eth0 = 'SSID' not in form if not use_eth0: form['SSID'] = form['SSID'].strip() form['Password'] = form['Password'].strip() else: form['SSID'] = 'using eth0' self.logger.debug('in Net POST: ' + form['SSID']) try: drop = 0 with open('/etc/network/interfaces', 'r') as infile: iface = infile.readlines() for line in iface: did_iface_wlan0 = False if drop > 0: drop -= 1 continue if 'iface ' + net + ' inet' in line: if net == 'wlan0': did_iface_wlan0 = True if 'Use DHCP' in form: self.logger.debug('Using dhcp: ' + form['SSID']) if 'static' in line: drop = 3 line = 'iface ' + net + ' inet manual\n' else: self.logger.debug('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway']) if 'static' in line: drop = 3 outdata.append('iface ' + net + ' inet static\n') outdata.append(' address ' + form['Static IP'] + '\n') outdata.append(' netmask ' + form['Netmask'] + '\n') line = ' gateway ' + form['Gateway'] + '\n' outdata.append(line) if did_iface_wlan0: outdata.append( ' wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n' ) except Exception as ex: self.logger.exception( 'Unexpected exception trying to configure network: ' + str(ex)) raise web.seeother('/cn') if len(outdata) == 0: self.logger.error('Expected data in /etc/network/interfaces') raise web.seeother('/cn') self.logger.debug( 'stopping daemons before updating network interfaces') # if not use_eth0: # stop_daemons() try: with open('/etc/network/interfaces', 'w') as outfile: outfile.writelines(outdata) if not use_eth0: wpa_supp_lines = [ 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n' ] wpa_supp_lines.append('update_config=1\n\n') if form['SSID'] != '' and form['Password'] != '': # wpa_passphrase cannot handle blanks cmd = 'wpa_passphrase ' + form['SSID'] + ' ' + form[ 'Password'] + ' > passphrase' subprocess.call(cmd, shell=True) with open('passphrase', 'r') as f: pl = f.readlines() for line in pl: wpa_supp_lines.append(line) if using_hidden_ssid and 'ssid' in line: wpa_supp_lines.append('\tscan_ssid=1\n') subprocess.call(['rm', 'passphrase']) else: self.logger.warning('missing ssid or password') with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile: outfile.writelines(wpa_supp_lines) # check if network connection was made self.logger.debug('wpa_action stopping wlan0') rc = subprocess.call(['wpa_action', 'wlan0', 'stop']) self.logger.debug('wpa_action return: ' + str(rc)) time.sleep(1) self.logger.debug('ifup wlan0') rc = subprocess.call(['ifup', net]) self.logger.debug('ifup return: ' + str(rc)) time.sleep(2) if network_up(net): #successful network connection. Finalize # copy the current versions to the save version if gv.sd['enable_upnp']: # was enabled? Then cleanup cur_ip = get_ip(net) deletes = [] if gv.sd['external_htp'] != 0: deletes.append(gv.sd['external_htp']) if gv.sd['remote_support_port'] != 0: deletes.append(gv.sd['remote_support_port']) update_upnp(cur_ip, deletes) gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0 if gv.sd['enable_upnp']: if 'UPnP Refresh Rate' in form: gv.sd['upnp_refresh_rate'] = int( form['UPnP Refresh Rate']) if 'System Name' in form: gv.sd['name'] = form['System Name'] jsave(gv.sd, 'sd') if 'System Port' in form: gv.sd['htp'] = int(form['System Port']) jsave(gv.sd, 'sd') if 'External System Port' in form: gv.sd['external_htp'] = int(form['External System Port']) self.logger.info('success....copying back interfaces and wpa') shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save') shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save') # self.logger.info('success....enabling boiler') # subprocess.call(['update-rc.d', 'boiler', 'defaults']) # self.logger.info('disabling boiler_net_finish') # subprocess.call(['update-rc.d', 'boiler_net_finish', 'remove']) self.logger.info('rebooting') subprocess.call(['reboot', '-h']) exit(0) else: raise Exception('Network Inaccessible') except Exception as ex: self.logger.exception('failed: ' + str(ex)) # restore saved /etc/network/interfaces and wpa_suplicant.conf self.logger.info('restore network files and exit. Exception: ' + str(ex)) shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces') shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf') exit(1) self.logger.error( 'boiler_net_config: should have exited above. boiler_monitor will restart' ) raise web.seeother('/')