def start(self, network): self.stop() profile = network.profile if not 'encryption_type' in network.profile: raise WicdError('Network profile does not specify encryption type') encryption_type = network.profile['encryption_type'] template_class = self.template_manager.get_template(encryption_type) if not template_class: raise WicdError('Template type %s does not exist' % encryption_type) values = {} for requirement in template_class.require: if requirement.name in profile: values[requirement.name] = str(profile[requirement.name]) else: raise WicdError('Missing required value %s' % requirement.name) values['essid'] = network.essid values['scan'] = 0 log('wpa_supplicant values', values) wpa_conf_name = network.bssid.replace(':', '').lower() wpa_conf_name += 'vpb' self.create_configuration_file(wpa_conf_name, template_class, values) pathname = os.path.join(wpath.networks, wpa_conf_name) self.wpa_supplicant = misc.run([ misc.find_program_in_path('wpa_supplicant'), '-i', self.interface_name, '-D', 'wext', '-c', pathname ], return_fileobject=True)
def _do_connect(abort_if_needed, interface, network): log('connecting to network', network.bssid) interface.reset() interface.up() interface.set_up_encryption(network) got_ip = interface.do_ip_address(network.profile) log('%s: interface got IP: %s' % (interface.interface_name, got_ip))
def do_ip_address(self, profile): if 'use_static_ip' in profile \ and profile['use_static_ip']: log('do static ip') ip_addresses = ['static_ip', 'static_netmask', 'static_dns_1'] optional = ['static_gateway', 'static_dns_2', 'static_dns_3'] for field in ip_addresses + optional: if not field in profile: raise misc.WicdError('Missing required profile item %s' % field) for field in ip_addresses: if not misc.is_valid_ip(profile[field]): raise misc.WicdError('Invalid IP address: %s' % network.profile[field]) for field in optional: if not profile[field] is None: if not misc.is_valid_ip(profile[field]): raise misc.WicdError('Invalid IP address: %s' % profile[field]) self.set_ip(profile['static_ip']) self.set_netmask(profile['static_netmask']) if profile['static_gateway']: self.set_gateway(profile['static_gateway']) return True else: log('using dhcp') self.dhcp_manager.start() return self.dhcp_manager.status()
def load_backend(self, backend_name): """ Load and return a backend module. Given a backend name be-foo, attempt to load a python module in the backends directory called be-foo. The module must include a certain set of classes and variables to be considered valid. """ def fail(backend_name, reason): log("failed to load backend %s: %s" % (backend_name, reason)) log("trying to load backend %s" % backend_name) backend_path = os.path.join(self.backend_dir, "be-" + backend_name) if self._valid_backend(backend_path): sys.path.insert(0, self.backend_dir) backend = __import__("be-" + backend_name) else: fail(backend_name, "invalid backend file.") return None new_backends = [i for i in dir(backend.interface) if i.startswith("Backend")] for backend_class_name in new_backends: backend_class = getattr(backend.interface, backend_class_name) if issubclass(backend_class, BaseInterface): self.__loaded_backends[backend_class.get_type()] = backend_class log("successfully loaded backend %s" % backend_class.__name__) else: fail(backend_class, "does not subclass BaseInterface")
def _run_autoconnect(self, value, interface_name): log( 'running _run_autoconnect...', value) if interface_name is None: for interface_name in self.daemon.ListInterfaces(): self._autoconnect_interface(value, interface_name) else: self._autoconnect_interface(value, interface_name)
def stop(self): if hasattr(self, 'dhclient'): log('killing dhclient %s' % self.dhclient.pid) os.kill(self.dhclient.pid, 15) else: log('no dhclient running') if hasattr(self, '_last_status'): del self._last_status
def main(): run = True startButton = Button(env.startButton, pull_up=False) stopButton = Button(env.stopButton, pull_up=False) try: while True: # Run forever if startButton.is_pressed and stopButton.is_pressed: f = logfile.openfile() logfile.log(f, datetime.datetime.now(), 4, True) f.close() elif startButton.is_pressed and not race.running(): runInParallel(leds.countdown, buzzer.countdown) race.start() while race.running() and not stopButton.is_pressed: time.sleep(0.2) if stopButton.is_pressed and race.running(): race.stop() if not stopButton.is_pressed and not race.running(): runInParallel(leds.finish, buzzer.finish) race.wait() time.sleep(0.2) except KeyboardInterrupt: print('Goodbye !!!') if race.running(): race.stop()
def GetInterfaceData(self, interface_name, method_name, data): ''' Gets the specified data from the specified interface. ''' data = self.interface_action(interface_name, method_name, data, 'get_') if data in [(), [], {}]: data = ('dbusdoesntallowemptytuples',) log( 'returning', data ) return data
def find_location(self): for location in self.locations: results = location.run_tests() log( location,'results:',results ) if True in results and not False in results: return location raise self.NoLocationFoundError('No location was detected.')
def perform(self): self._test_interface_type_has_method() interfaces = get_all_by_type(self.interface_type) for interface in interfaces: try: getattr(interface, self.method_name)(self.data) except WicdError, e: log( 'error occured while running %s: %s' % (self.method_name, e))
def wait(): global threads, f for t in threads: t.join() logfile.log(f, datetime.datetime.now(), 3, True) f.close() cleanup()
def _get_numbered_items_by_location(self, item_base, location): items = [] for name, value in self.items(location): if name.startswith(item_base): try: items.insert(int(name[len(item_base):]), value) except ValueError: log( '%s is not a valid item' % name ) return items
def receive_data(self): global _dataBufferSize received = b'' # Starts receiving while not self.transfer_complete: received += self.socket.recv(_dataBufferSize) received += _receive_rest(self.socket) log("Received " + str(len(received)) + " bytes") return received
def get_all_files(folder): log("Scanning local directory...") res = [] for f in os.listdir(folder): abspath = os.path.join(folder, f) if os.path.isfile(abspath): res.append((f, os.path.getsize(abspath))) log("Found " + str(len(res)) + " files in the local directory") return res
def refresh(self, button=None): log( 'Refreshing...') ui = dbus_ifaces['interface'].GetInterfaceData('wired1', 'user_interface') cbh = CallbackProxy('wired1') gtkinterface, controls = simpleinterface.generate_interface(ui, cbh) cbh.controls = controls log( gtkinterface) self.network_list.pack_start(gtkinterface.control) self.network_list.show_all()
def load_netutils(self, name): if name in self.find_available_netutils(): log('loading netutils %s' % name) if name.endswith('.py'): name = name[:-3] module = __import__('netutilsbackends.' + str(name)) module = getattr(module, name) return module else: raise WicdError('Netutils %s was not found' % name)
def check_status(self): interfaces = self.daemon.interface_manager.get_all_by_type('wired') for interface in interfaces: link = interface.get_has_link() if link: if self.last_status.get(interface, False) is False: log( '%s: interface got link' % interface.interface_name) self.daemon.plugin_manager.action('got_link', (interface, )) self.last_status[interface] = link return True
def run(self): try: result = self.copied_method(self.abort_if_needed, *self.copied_args) except: log( 'error occurred in AsyncRunner, exiting thread...') self.error_flag.set() result = None raise finally: self.result = result self.done_event.set() log( '%s: AsyncRunner thread exited' % self.copied_method.func_name)
def perform(self): self._test_interface_type_has_method() interfaces = get_all_by_type(self.interface_type) passed = [] for interface in interfaces: result = False try: result = getattr(interface, self.method_name)() except WicdError, e: log( 'error occured while running %s: %s' % (self.method_name, e)) else: passed.append(self._recursive_find(result, self.data))
def __line_received(line): global __callbacks global __cblock log(line, "<< ") # Locks the list of callbacks during the processing __cblock.acquire() # Goes through the filters and triggers the actions for the filters that match for filter, action in __callbacks: if filter(line): action(line) __callbacks.remove((filter, action)) __cblock.release()
def create_configuration_file(self, filename, template_class, values): wpa_supplicant_template = str(template_class.template) for key, value in values.iteritems(): value = str(value) find = "$_%s" % key.upper() log('replacing %s with %s' % (find, value)) wpa_supplicant_template = \ wpa_supplicant_template.replace(find, value) pathname = os.path.join(wpath.networks, filename) log('writing wpa_supplicant configuration file %s' % pathname) the_file = open(pathname, 'w') the_file.write(wpa_supplicant_template) the_file.close()
def shut_down(): try: global child_pid, daemon log( 'Sending Closing signal...' ) daemon.Closing() daemon.SaveConfiguration() log( 'Removing PID file...') if os.path.exists(wpath.pidfile): os.remove(wpath.pidfile) log( 'Shutting down...') except Exception, e: log('Error occurred while shutting down:') log('\t', e)
def create(self, type, interface_name): """ Creates the interface, if possible. If interface exists, returns. """ if not self.exists(interface_name): type_class = self.backend_manager.get_backend_by_type(type) def customized_callback(*args): return self.status_change_callback(interface_name, *args) new_interface = type_class(interface_name, customized_callback) self.add(new_interface) log("new interface: %s" % new_interface.interface_name) else: log("interface already exists: %s" % interface_name)
def start(): global threads, f, run_event setup() f = logfile.openfile() run_event.set() logfile.log(f, datetime.datetime.now(), 0, True) for sensor in env.sensors: t = threading.Thread(target=read_sensor, args=(sensor, f, run_event)) t.start() threads += [t]
def list_files(): global __serverIP # Establishes a data connection link = DataLink(__serverIP) # Asks for the files list send_request("LIST", startsWith="150") log("Receiving list of files...") # Receives the list rawData = link.receive_data().decode("ascii") files = __format_files_list(rawData) log("Found " + str(len(files)) + " files") # Closes the data connection link.close() return files
def scan(self): """ Updates the current wireless network list. """ self.save_profiles() self.current_network = None self.networks = self._do_scan() for network in self.networks: if self.config_manager.has_section(network.bssid): log(network.bssid,'has profile') settings = self.config_manager.items(network.bssid) network.profile = NetworkProfile(dict(settings)) else: log(network.bssid,'missing profile') network.profile = NetworkProfile() return self.networks
def load_all_plugins(self): classes = [] for plugin in self.find_available_plugins(): module = self.load_plugin(plugin) for item in dir(module): if item.endswith("Plugin") \ and not item == 'BasePlugin': the_class = getattr(module, item) classes.append(the_class) import operator classes.sort(key=operator.attrgetter('PRIORITY')) for the_class in classes: log( 'loading plugin %s' % the_class) self.loaded_plugins.append(the_class(self.daemon))
def RenameProcess(new_name): if sys.platform != 'linux2': log( 'Unsupported platform') return False try: import ctypes is_64 = os.path.exists('/lib64/libc.so.6') if is_64: libc = ctypes.CDLL('/lib64/libc.so.6') else: libc = ctypes.CDLL('/lib/libc.so.6') libc.prctl(15, new_name, 0, 0, 0) return True except: return False
def load(self): """ Loads the saved interface configuration. """ sections = self.config_manager.sections() for section in sections: interface_name = section type = self.config_manager.get_option(section, "type") try: self.create(type, interface_name) except baseinterface.BaseInterface.CannotCreateInterfaceException: log("error creating interface %s" % interface_name) log("skipping interface %s" % interface_name) else: interface = self.get(interface_name) for k, v in self.config_manager.items(section): setattr(interface, k, v)
def send_file(path, destName=None): global __serverIP if not destName: destName = __extract_name(path) # Establishes a data connection link = DataLink(__serverIP) # Asks for a file upload send_request("STOR " + destName) # Sends the file data datafile = open(path, "rb") filedata = datafile.read() log("Sending data from " + path + "...") link.send_data(filedata) datafile.close() # Closes the data connection link.close()
def fetch_file(name, destPath=None): global __serverIP if not destPath: destPath = name # Establishes a data connection link = DataLink(__serverIP) # Asks for a file download send_request("RETR " + name, startsWith="150") log("Receiving data from " + name + "...") # Receives the file filedata = link.receive_data() datafile = open(destPath, "wb+") datafile.write(filedata) datafile.close() # Closes the data connection link.close()
def main(argv): """ The main frontend program. Keyword arguments: argv -- The arguments passed to the script. """ use_tray = True animate = True try: opts, args = getopt.getopt(sys.argv[1:], 'nha', ['help', 'no-tray', 'no-animate']) except getopt.GetoptError: usage() sys.exit(2) for opt, a in opts: if opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-n', '--no-tray'): use_tray = False elif opt in ('-a', '--no-animate'): animate = False else: usage() sys.exit(2) log( 'Loading...') setup_dbus() if not use_tray: the_gui = gui.appGui() the_gui.standalone = True mainloop = gobject.MainLoop() mainloop.run() sys.exit(0) tray_icon = TrayIcon(use_tray, animate) if daemon.GetNeedWiredProfileChooser(): daemon.SetNeedWiredProfileChooser(False) tray_icon.icon_info.wired_profile_chooser() bus = dbus_manager.get_bus() bus.add_signal_receiver(tray_icon.icon_info.wired_profile_chooser, 'LaunchChooser', 'org.wicd.daemon') bus.add_signal_receiver(tray_icon.icon_info.update_tray_icon, 'StatusChanged', 'org.wicd.daemon') bus.add_signal_receiver(tray_icon.tr.tray_scan_ended, 'SendEndScanSignal', 'org.wicd.daemon.wireless') bus.add_signal_receiver(tray_icon.tr.tray_scan_started, 'SendStartScanSignal', 'org.wicd.daemon.wireless') log( 'Done.') mainloop = gobject.MainLoop() mainloop.run()
def read_sensor(sensor, f, run_event): laps_done = -1 # Si on detecte un passage, on enregistre # et on attend que la voiture soit passee while run_event.is_set() and laps_done < laps: state = GPIO.input(env.sensors[sensor]) if not state: # la voiture passe logfile.log(f, datetime.datetime.now(), sensor, True) laps_done += 1 while not state and run_event.is_set(): state = GPIO.input(env.sensors[sensor]) time.sleep(0.02) # Pause pour ne pas saturer le processeur # La voiture est passee time.sleep(0.02) # Pause pour ne pas saturer le processeur
def update_tray_icon(self, state=None, info=None): """ Updates the tray icon and current connection status. """ if not self.use_tray: return False if not state or not info: [state, info] = daemon.GetConnectionStatus() if state == misc.WIRED: self.set_wired_state(info) elif state == misc.WIRELESS: self.set_wireless_state(info) elif state == misc.CONNECTING: self.set_connecting_state(info) elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): self.set_not_connected_state(info) else: log( 'Invalid state returned!!!' ) return False return True
def open(ip): global __continue_listening global __socket # Connects the socket log("Connecting to " + ip + " at port 21...") __socket = socket.socket() __socket.settimeout(__connection_timeout) try: __socket.connect((ip, 21)) except: log("Could not connect to " + ip, "E: ") raise Exception("Could not connect to " + ip) __socket.settimeout(0.01) # Starts the listening thread __continue_listening = True thread = threading.Thread(target=__listen, args=(socket, )) thread.start()
def main(configFile): global config # Reads and apply the config file read_config(configFile) logfile.start(config['logs_file']) # Connects to the server host = config['host'] username = config['username'] password = config['password'] if not password: file = open(config['password_file'], "r") password = file.read() file.close() server.connect(host, username, password) # Gets the list of files on the server folder and in the local folder localfiles = localdir.get_all_files(config['local_dir']) serverfiles = server.list_files() # If a file have the same name on the client and the server but with different # size, backups the file on the server and uploads the client's version for lName, lSize in localfiles: for sName, sSize in serverfiles: if lName == sName and lSize != sSize: log("Backing up " + sName + "...") print("Backing up " + sName + "...") server.backup_file(sName) serverfiles.remove((sName, sSize)) # Downloads every file that is on the server but not in the local folder for file in serverfiles: if not file in localfiles: log("Downloading " + file[0] + "...") print("Downloading " + file[0] + "...") filepath = join(config['local_dir'], file[0]) if is_in_local_dir(filepath): server.fetch_file(file[0], filepath) # Protection against directory traversal else: log("Detected directory traversal attempt, aborting", "W: ") raise Exception("Detected directory traversal attempt\n" \ + filepath + " is not in the local directory") # Uploads everyfile that is in the local folder but not on the server for file in localfiles: if not file in serverfiles: log("Uploading " + file[0] + "...") print("Uploading " + file[0] + "...") server.send_file(join(config['local_dir'], file[0])) # Exits server.disconnect() print("Server and local dir are now synchronised!")
def find_program_in_path(program): """ Determines the full path for the given program. Searches a hardcoded list of paths for a given program name. Keyword arguments: program -- The name of the program to search for Returns: The full path of the program or None """ try: paths = os.environ['PATH'].split(':') except: log( 'using $PATH failed, using preselected locations') paths = ['/sbin/', '/usr/sbin/', '/bin/', '/usr/bin/', '/usr/local/sbin/', '/usr/local/bin/'] for path in paths: if os.access(os.path.join(path, program), os.F_OK): return os.path.join(path, program) return None
def get_option(self, section, option, default=None): """ Wrapper around ConfigParser.get. Automatically adds any missing sections, adds the ability to write a default value, and if one is provided prints if the default or a previously saved value is returned. """ if not self.has_section(section): self.add_section(section) if self.has_option(section, option): ret = ConfigParser.get(self, section, option) if default: log( ''.join(['found ', option, ' in configuration ', ret])) else: log( ''.join(['did not find ', option, ' in configuration, setting default ', str(default)])) self.set(section, option, str(default), save=True) ret = default return misc.smart_type(ret)
def setup_dbus(): global bus, daemon, wireless, wired, dbus_manager dbus_manager = DBusManager() try: dbus_manager.connect_to_dbus() except DBusException: log( "Can't connect to the daemon, trying to start it automatically..." ) misc.PromptToStartDaemon() try: dbus_manager.connect_to_dbus() except DBusException: gui.error(None, "Could not connect to wicd's D-Bus interface. " + "Make sure the daemon is started.") sys.exit(1) dbus_ifaces = dbus_manager.get_dbus_ifaces() daemon = dbus_ifaces['daemon'] wireless = dbus_ifaces['wireless'] wired = dbus_ifaces['wired'] return True
def _freq_to_channel(self, freq): """ Translate the specified frequency to a channel. Note: This function is simply a lookup dict and therefore the freq argument must be in the dict to provide a valid channel. Keyword arguments: freq -- string containing the specified frequency Returns: The channel number, or None if not found. """ ret = None freq_dict = {'2.412 GHz': 1, '2.417 GHz': 2, '2.422 GHz': 3, '2.427 GHz': 4, '2.432 GHz': 5, '2.437 GHz': 6, '2.442 GHz': 7, '2.447 GHz': 8, '2.452 GHz': 9, '2.457 GHz': 10, '2.462 GHz': 11, '2.467 GHz': 12, '2.472 GHz': 13, '2.484 GHz': 14 } try: ret = freq_dict[freq] except KeyError: log("Couldn't determine channel number for frequency: " + str(freq)) return ret
def __listen(socket): global __continue_listening global __line_ending global __commandBufferSize received = b'' log("Started listening to the command socket") while __continue_listening: # Receives data try: received += __socket.recv(__commandBufferSize) except: continue # If the data contains the line ending, splits it and calls __line_received index = received.find(__line_ending) while index != -1: __line_received(received[:index].decode("ascii")) received = received[index + len(__line_ending):] index = received.find(__line_ending) log("Stopped listening to the command socket") return received
def __init__(self, ip): global _connection_timeout global _transmission_timeout # Establishes a data connection pasvResp = send_request("PASV", startsWith="227") dataPort = _decode_pasv(pasvResp) log("Connecting data channel at port " + str(dataPort) + "...") self.socket = socket.socket() self.socket.settimeout(_connection_timeout) self.socket.connect((ip, dataPort)) self.socket.settimeout(_transmission_timeout) # Sets up a callback to know when the transfer is done self.transfer_complete = False def action(line): nonlocal self self.transfer_complete = True filter = lambda line: line.startswith("226") commandlink.add_callback(action, filter)
def interface_action(self, interface_name, method_name, data, prefix=''): ''' Runs a specified action on a specified method that starts with prefix. ''' if not self.interface_manager.exists(interface_name): raise WicdError('Specified interface does not exist') interface = self.interface_manager.get(interface_name) if not hasattr(interface, (prefix + method_name)): raise WicdError('%s: method does not exist' % (prefix + method_name)) self.plugin_manager.action('starting_action', (interface_name, (prefix + method_name), self._has_data(data))) method = getattr(interface, prefix + method_name) log ( '%s interface action calling %s' % (prefix[:-1], method) ) return_data = None if self._has_data(data): return_data = method(*data) else: return_data = method() self.plugin_manager.action('finished_action', (interface_name, (prefix + method_name), self._has_data(data), return_data)) return return_data
def _parse_access_point(self, cell): """ Parse a single cell from the output of iwlist. Keyword arguments: cell -- string containing the cell information Returns: A dictionary containing the cell networks properties. """ ap = WirelessNetwork() ap.essid = misc.run_regex(WirelessRegexPatterns.essid, cell) try: ap.essid = misc.to_unicode(ap.essid) except (UnicodeDecodeError, UnicodeEncodeError): log('Unicode problem with current network essid, ignoring!!') return None if ap.essid in ['<hidden>', ""]: ap.essid = 'Hidden' ap.hidden = True else: ap.hidden = False ap.channel = misc.run_regex(WirelessRegexPatterns.channel, cell) if ap.channel == None: freq = misc.run_regex(WirelessRegexPatterns.freq, cell) ap.channel = self._freq_to_channel(freq) ap.bssid = misc.run_regex(WirelessRegexPatterns.ap_mac, cell) ap.mode = misc.run_regex(WirelessRegexPatterns.mode, cell) if (WirelessRegexPatterns.strength.match(cell)): [(strength, max_strength)] = WirelessRegexPatterns.strength.findall(cell) if max_strength: ap.quality = 100 * int(strength) // int(max_strength) else: ap.quality = int(strength) elif misc.run_regex(WirelessRegexPatterns.altstrength,cell): ap.quality = misc.run_regex(WirelessRegexPatterns.altstrength, cell) else: ap.quality = -1 if misc.run_regex(WirelessRegexPatterns.signaldbm, cell): ap.strength = misc.run_regex(WirelessRegexPatterns.signaldbm, cell) return ap
def send_request(request, filter=None, startsWith=None): global __socket global __request_timeout # Sets a callback to know when the response has arrived* response = None def action(line): nonlocal response response = line if startsWith: filter = lambda line: line.startswith(startsWith) add_callback(action, filter) # Sends the request __socket.send(bytes(request, "ascii") + b"\r\n") log(request, ">> ") # Blocks while the response is not received start = time.time() while response is None: if time.time() - start > __request_timeout: log("Didn't receive response for request: " + request, "E: ") raise Exception("Didn't receive response for request: " + request) time.sleep(0.005) # Returns the response return response
def connect(hostname, user, password): global __serverIP global __hostName global __timeout global __username global __password global __storageDir # Finds the ip address log("Finding ip of host " + hostname + "...") try: ip = socket.gethostbyname(hostname) except: log("Could not resolve host " + hostname, "E: ") raise Exception("Could not resolve host " + hostname) __serverIP = ip # Opens the command link and sets the data link up commandlink.open(ip) # Sends the authentication messages send_request("AUTH SSL", startsWith="530") send_request("USER " + user, startsWith="331") send_request("PASS " + password, startsWith="230") # Sets the connection up send_request("TYPE I", startsWith="200") __change_directory(__storageDir)
def disconnect(): log("Disconnecting...") commandlink.close()
def close(self): port = str(self.socket.getpeername()[1]) self.socket.close() log("Closed data channel at port " + port)
Tacq = 10 # Measurement time in seconds CoincidenceWindow = 10e-9 # Coincidence window based on observed delay between row and column pulses. # Setup Laser and Attenuators laser.setWavelength(LaserWvl) laser.setPower(LaserPwr) laser.setModeCW() Attn1.set_att(LaserAttn1) Attn2.set_att(LaserAttn2) Attn1.set_lambda(LaserWvl) Attn2.set_lambda(LaserWvl) # File I/O Stuff dataLogPath = options['networkData&LogPath'] L = logfile.log() L.UQD(sys.argv, config, uqdConfig) #Run UQDinterface #args = ['sudo', '../../CppDemo/UQDinterface', '&'] #args = ['sudo', 'bash','launch.sh'] #f = open('test','w') #p = subprocess.Popen(args,stdout=f) #p = subprocess.Popen(args) print "The process ID is:" #print p.pid+1 # p.pid is the PID for the new shell. p.pid is the PID for UQDinterface in the new shell #print p.pid+2 #time.sleep(1) #ttnumber = int(raw_input("Time tagger to open:"))