Example #1
0
    def load(self, name):
        self.__lock.acquire()
        try:
            passwd_db = PasswdFile(self.__password_file)
            passwd_db.load()
            if name in passwd_db:
                self.__user = passwd_db[name]
            else:
                self.__user = None
                raise EInvalidValue('name', name, 'No such user.')
            self.__file_modified = passwd_db.last_modified()

            # loading /etc/shadow database
            shadow_db = ShadowFile(self.__shadow_file)
            shadow_db.load()
            if name in shadow_db:
                self.__shadow = shadow_db[name]
            else:
                self.__shadow = None
                raise EInvalidValue('User (', name,
                                    ') does not exist in shadow')
            self.__shadow_file_modified = shadow_db.last_modified()

            self.__loaded = 1
        finally:
            self.__lock.release()
Example #2
0
 def load(self, name):
     self.__lock.acquire()
     try:
         passwd_db = PasswdFile(self.__password_file)
         passwd_db.load()
         if name in passwd_db:
             self.__user = passwd_db[name]
         else:
             raise EInvalidValue('name', name, 'No such user.')
         shadow_db = ShadowFile(self.__shadow_file)
         shadow_db.load()
         if name in shadow_db:
             self.__shadow = shadow_db[name]
         else:
             raise EInvalidValue('name', name, 'No such user.')
         self.__groups = []
         groups_db = GroupFile(self.__group_file)
         groups_db.load()
         for group_name in self.__user.groups(groups_db):
             self.__groups.append(groups_db[group_name])
         if not self.__groups:
             raise EInvalidValue('name', name, 'User belongs to no groups.')
         self.__loaded = 1
     finally:
         self.__lock.release()
Example #3
0
 def start(self):
     CompositeNode.start(self)
     self.local_context = {}
     try:
         self.compiled_statement = compile(self.statement, '', 'eval')
         #examine each variable and decide what to do with it
         for variable in self.variables:
             name = variable['vn']
             definition = variable['node_reference']
             if self.local_context.has_key(name):
                 raise EInvalidValue('variable', name,
                                     'Variable name duplicated')
             exceptions = []
             conversions = self._conversions[:]
             while conversions:
                 conversion = conversions.pop(0)
                 try:
                     reference = conversion(definition)
                     break
                 except Exception, e:
                     exceptions.append(e)
             else:
                 self.local_context = {}
                 raise EInvalidValue('variable', name,
                                     ('Conversions %s Gave Errors %s.' %
                                      (self._conversions, exceptions)))
             self.local_context[name] = reference
         self.started = 1
Example #4
0
 def _check_parameters(self, column, start, end):
     if column != '_seq':
         raise EInvalidValue('column', column,
                             'Value of column must be _seq')
     if end is not None:
         raise EInvalidValue('end', end, 'Value of end must be None')
     if start >= 0:
         raise EInvalidValue('start', start,
                             'Value of start must be less than 1')
Example #5
0
 def _decode_to_dbcs(self, buffer):
     if ord(buffer[0]) != DBCS:
         raise EInvalidValue('buffer', buffer, 'Not a DBCS encoding')
     if len(buffer) < 3:
         raise EInvalidValue('buffer length must be at least' +
                             ' three bytes long')
     self.character_set = ord(buffer[0])
     self.code_page = (ord(buffer[1]) << 8) + ord(buffer[2])
     self.character_string = buffer[3:]
     self.__class__ = DBCS_String
Example #6
0
 def decode(self, buffer):
     if len(buffer) != 6:
         raise EInvalidValue('decode',
                             buffer,
                             text='length of buffer must be 6')
     self.encoding = buffer
     if ord(self.encoding[1]) != 0x00:
         raise EInvalidValue('function_code',
                             self.encoding[1],
                             text='Result function code must be 0')
     self.result_code = _str_as_ushort(self.encoding[4:6])
Example #7
0
 def decode(self, buffer):
     if len(buffer) < 4:
         raise EInvalidValue('buffer',
                             buffer,
                             text='length of buffer must at least 4')
     self.encoding = buffer  #just a default encoding
     self.length = _bvlc_length(self.encoding)
     if self.length != len(buffer):
         raise EInvalidValue('buffer', buffer, text='length field mismatch')
     self.number_of_entries = (self.length - 4) / 10
     self.entries = []
     for i in range(self.number_of_entries):
         self.entries.append(
             BDT_Entry(decode=self.encoding[i * 10 + 4:i * 10 + 14]))
Example #8
0
 def convert(self):
     look_up_tbl = [
         481.8, 404.1, 363.8, 337.2, 317.6, 302.1, 289.4, 278.6, 269.3,
         261.2, 253.9, 247.3, 241.4, 235.9, 230.9, 226.2, 221.8, 217.7,
         213.9, 210.3, 206.9, 203.6, 200.5, 197.5, 194.7, 192, 189.4, 186.9,
         184.5, 182.2, 180, 177.8, 175.7, 173.7, 171.7, 169.8, 167.9, 166.1,
         164.4, 162.7, 161, 159.4, 157.8, 156.2, 154.7, 153.2, 151.7, 150.3,
         148.9, 147.5, 146.2, 144.8, 143.5, 142.3, 141, 139.8, 138.5, 137.4,
         136.2, 135, 133.9, 132.7, 131.6, 130.5, 129.4, 128.4, 127.3, 126.3,
         125.3, 124.2, 123.2, 122.2, 121.3, 120.3, 119.3, 118.4, 117.4,
         116.5, 115.6, 114.7, 113.8, 112.9, 112, 111.1, 110.2, 109.4, 108.5,
         107.7, 106.8, 106, 105.1, 104.3, 103.5, 102.7, 101.9, 101.1, 100.3,
         99.5, 98.7, 97.9, 97.1, 96.4, 95.6, 94.8, 94.1, 93.3, 92.5, 91.8,
         91, 90.3, 89.6, 88.8, 88.1, 87.4, 86.6, 85.9, 85.2, 84.5, 83.7, 83,
         82.3, 81.6, 80.9, 80.2, 79.5, 78.8, 78.1, 77.4, 76.7, 76, 75.3,
         74.6, 73.9, 73.2, 72.5, 71.8, 71.1, 70.4, 69.7, 69, 68.4, 67.7, 67,
         66.3, 65.6, 64.9, 64.2, 63.5, 62.8, 61.5, 60.8, 60.1, 59.4, 58.7,
         58, 57.3, 56.6, 55.9, 55.2, 54.5, 53.8, 53.1, 52.4, 51.7, 51, 50.3,
         49.6, 48.8, 48.1, 47.4, 46.7, 45.9, 45.2, 44.5, 43.7, 43, 42.3,
         41.5, 40.8, 40, 39.3, 38.5, 37.7, 36.9, 36.2, 35.4, 34.6, 33.8, 33,
         32.2, 31.4, 30.6, 29.7, 28.9, 28.1, 27.2, 26.4, 25.5, 24.6, 23.7,
         22.9, 22, 21, 20.1, 19.2, 18.2, 17.3, 16.3, 15.3, 14.3, 13.3, 12.3,
         11.2, 10.2, 9.1, 8, 6.9, 5.7, 4.6, 3.4, 2.2, 0.9, -0.3, -1.6, -2.9,
         -4.3, -5.7, -7.1, -8.6, -10.2, -11.7, -13.4, -15.1, -16.8, -18.6,
         -20.5, -22.5, -24.6, -26.8, -29.1, -31.6, -34.2, -37, -40.1, -43.4,
         -47, -51.1, -55.7, -61, -67.3, -75.2, -86, -86, 254, 254
     ]
     try:
         s_temp = look_up_tbl[self.ion.get()]
         return s_temp
     except:
         raise EInvalidValue('value out of range', offset, 'convert()')
Example #9
0
 def security_data(self, **overrides):
     original = self.keywords()
     keywords = original.copy()
     keywords.update(overrides)
     hashed = 0
     if self._a1_base is not None and keywords['realm'] == original['realm']:
         A1_base = self._a1_base
     else:
         A1_base = '%s:%s:%s' % (self.user.name(), keywords['realm'],
                                 self.user.password())
     A1 = A1_base
     if keywords.has_key('algorithm'):
         if keywords['algorithm'] == 'MD5':
             pass
         elif keywords['algorithm'] == 'MD5-sess':
             hashed = 1
             A1_base = md5.new(A1_base).hexdigest()
             A1 = '%s:%s:%s' % (A1_base, keywords['nonce'],
                                keywords['cnonce'])
         else:
             raise EInvalidValue(
                 'algorithm', keywords['algorithm'],
                 'Algorithm must be blank, MD5, or MD5-sess')
     if not overrides:
         self._a1_base = A1_base
         self._a1_base_hashed = hashed
     return A1
Example #10
0
 def makefile(self,mode='r',bufsize=0):
     if bufsize != 0:
         raise EInvalidValue('bufsize',bufsize,
                             'To ensure safety, '
                             'bufsize must be 0')
     file = self._socket.makefile(mode,0)
     return _SockFile(self,file)
Example #11
0
 def configure(self, config):
     set_attribute(self, 'debug', 0, config, int)
     set_attribute(self, 'ip', '', config)
     default = '${mpx.properties.%s_PORT}' % self.server_type
     set_attribute(self, 'port', default, config, int)
     set_attribute(self, 'user_manager', as_node('/services/User Manager'),
                   config, as_node)
     set_attribute(self, 'authentication', 'form', config)
     if (self.authentication is not None
             and self.authentication not in ('digest', 'basic', 'form')):
         raise EInvalidValue('authentication', self.authentication,
                             'Authentication scheme not recognized.')
     set_attribute(self, 'port', default, config, int)
     set_attribute(self, 'maintenance_interval', 25, config, int)
     set_attribute(self, 'zombie_timeout', 600, config, int)
     set_attribute(self, 'thread_count', 3, config, int)
     if not self.has_child("Request Responder"):
         self._setup_request_responder()
     if not self.has_child("Authenticator"):
         self._setup_authentication_handler()
     if not self.has_child("PSP Handler"):
         self._setup_psp_handler()
     if not self.has_child("JSON-RPC Handler"):
         self._setup_json_handler()
     ServiceNode.configure(self, config)
Example #12
0
 def __init__(self, *args, **keywords):
     if keywords.has_key('decode'):
         self.decode(keywords['decode'])
     elif len(args) == 0:
         self.encode()
     else:
         raise EInvalidValue('requires no parameters or decode=')
Example #13
0
    def read_nodedef_db(self, compression_algorithm=NONE):
        f = None
        try:
            if compression_algorithm == self.NONE:
                try:
                    f = open(
                        os.path.join(self.BROADWAY_ROOT,
                                     self.NODEDEF_DBFILE_EN))
                except IOError:
                    f = self._open_nodedef_db()
                    self._copy_encoded(
                        f,
                        os.path.join(self.BROADWAY_ROOT,
                                     self.NODEDEF_DBFILE_EN))

                    f.close()
                    f = None
                    f = open(
                        os.path.join(self.BROADWAY_ROOT,
                                     self.NODEDEF_DBFILE_EN))
            elif compression_algorithm == self.ZIP:
                f = open(os.path.join(self.BROADWAY_ROOT,
                                      self.NODEDEF_ZIPFILE))
            else:
                raise EInvalidValue('compression_algorithm',
                                    compression_algorithm)
            return BinaryString(f.read())
        except IOError, ie:
            if f: f.close()
            raise MpxException('Could not read nodedef database: %s' % str(e))
Example #14
0
 def read(self,buffer,count=None,timeout=None):
     if self.raw_mode:
         return self._raw_read(buffer,count,timeout)
     elif count is None:
         raise EInvalidValue('count',count,
                             'In non-raw mode count most not be None')
     return self._fancy_read(buffer,count,timeout)
Example #15
0
def create_server_device(node, network, carrier_mtu=1476):
    #print 'create server device: ', node.as_node_url(), network, carrier_mtu
    the_device = _DeviceInfo(carrier_mtu)
    the_device.instance_number = node.instance
    the_device.node = node
    the_device.network = network
    the_device.mac_network = network
    interface = node.get_interface()
    if interface is None:
        # virtual device.  Modify Addr with an address equal to the intance number
        the_device.address.address = utils.bytes_as_string_of_hex_values(
            the_device.instance_number, 6)
    else:
        # real device.  Use Interface's Addr
        the_device.address = interface.addr  #the_device.address
        #only one real device is allowed for an interface
        if interface.master_device is not None:
            raise EInvalidValue(
                "BACnet server device misconfigured", str(network),
                '''Only one device with the Interface's network number is allowed.
Existing device: %s
New device: %s''' % (
                    interface.master_device.node.as_node_url(),
                    node.as_node_url(),
                ))
        interface.master_device = the_device
    the_device.mac_address = the_device.address
    # the following two lines need to be generalized for multiple internetworks
    the_devices[
        the_device.
        instance_number] = the_device  #add to list, key by instance number aka mac address
    _network.add_server_to_device_table(
        the_device)  #copy client since it won't see this
    if debug: print 'the server device has been created: %s' % str(the_device)
    return the_device
Example #16
0
 def clear_subscr(self, targets=None):
     if self.line_handler is None:
         return
     if (type(targets) == types.ListType):
         targets0_type = type(targets[0])
         if (targets0_type == types.TupleType):
             pass
         elif (targets0_type == types.StringType):
             new_targets = []
             for node_URL in targets:
                 node = None
                 try:
                     node = as_node(node_URL)
                 except ENoSuchName:
                     msglog.exception()
                     continue
                 new_targets.append((
                     node.lan_address,
                     node.id_number,
                 ))
             if len(new_targets) == 0:
                 return
             targets = new_targets
         else:
             raise EInvalidValue('targets',targets,'Should be None, int, ' \
                                 'or list of 2-tuples (dev_id, obj_id) or ' \
                                 'a list of node URL strings.')
     self.line_handler.clear_subscr(targets)
     return
Example #17
0
 def __init__(self, index=-1):
     if index == -1:
         t = 'index must be in the range 0-8'
         raise EInvalidValue('index', str(index), text=t)
     else:
         self.index = index
     super(TimeAttribute, self).__init__()
Example #18
0
 def _run_who_is(self):
     print 'starting aerocomm server who is message thread'
     if self.transceiver_state != 2:
         self._reset_aerocomm_transceiver()
     time.sleep(5)
     self.send((self.driver.all, self._who_is_message(),))
     if self.transceiver_state != 2:
         raise EInvalidValue('transceiver_state',self.transceiver_state, \
                             'Transceiver not responding. Restart whois thread.') # force thread to restart
     time.sleep(10)
     self.send((self.driver.all, self._who_is_message(),))
     counter = 0
     bad_state_counter = 0
     while self._running:
         try:
             if counter > 30: # 5 minutes
                 counter = 0 
                 if self.debug: print 'send who is'
                 self.send((self.driver.all, self._who_is_message(),))
             else:
                 counter += 1
             if self.transceiver_state == 2:
                 bad_state_counter = 0 #things is good
             else:
                 print 'aerocomm server transceiver status not good'
                 bad_state_counter += 1
                 if bad_state_counter > 2:
                     raise EConnectionError('aerocomm server transceiver status not good') #force thread to restart
         except Exception, e:
             print '**** aerocomm whois message exception ****', str(e)
             time.sleep(5)
             raise
         time.sleep(self.who_is_interval)
Example #19
0
 def set_ee_parameter(self, name, value):
     addr, length, rw, type, _range, desc = self.eeprom_parameters[name]
     if rw == 0:
         raise EPermission('attempt to set read only parameter', addr,
                           'Aerocomm driver')
     if type == MAC:
         return self.write_ee(addr, length, MacAddress(value).value)
     if type == BIT:
         old_value = self.get_ee_parameter(name)
         pos, len = _range
         old_value &= _bitfield_mask(pos,
                                     len)  #clean out bits for new value
         value = _int2bitfield(value, pos, len)
         value |= old_value
         type = INT
     if type == HEX or type == INT:
         value = int(value)
         s = []
         for i in range(length):
             s.append(value & 255)
             value = value // 256
         s.append(str(length) + 'B')
         s.reverse()
         answer = apply(struct.pack, s)
         return self.write_ee(addr, length, answer)
     raise EInvalidValue('unknown type', type, 'aerocomm set_ee_parameter')
Example #20
0
def send_request(host, post, action, soap_request, conn=None):
    header = {'SOAPAction': action, 'Content-Type': 'text/xml; charset=utf-8'}
    i = host.find('http://')
    if i >= 0:
        host = host[i + 7:]  #remove leading http if present
    if host[-1] == '/':
        host = host[:-1]
    if post[0] != '/':  #make sure post starts with /
        post = '/' + post
    if post[-1] == '/':
        post = post[:-1]
    #if debug: print host, post, action, soap_request
    close_conn = 0
    if conn is None:
        conn = _HTTPConnection(host)
        close_conn = 1
    conn._trace('instantiated')
    conn._continuations = 0
    if conn is None:
        if debug: print 'host not found'
        raise ETimeout('host not found', (host, post, action, soap_request))
    try:
        if debug > 2: conn.set_debuglevel(1)
        conn._trace('pre-request')
        conn.request('POST', post, soap_request, header)
        conn._trace('post-request')
        while 1:
            conn._trace('pre-getresponse')
            r = conn.getresponse()
            if debug: print r.status, r.reason
            conn._trace('post-getresponse')
            if r.status != 100:
                break
            _HTTPConnection._total_continuations += 1
            conn._continuations += 1
            # 2000-12-30 djf -- drop bogus 100 response
            # by kludging httplib
            conn._HTTPConnection__state = httplib._CS_REQ_SENT
            conn._HTTPConnection__response = None
        if r.status != 200:
            raise EInvalidResponse(str(r.status), 'expecting OK response',
                                   (host, post, action, soap_request))
        conn._trace('pre: r.read()')
        response = r.read()
        conn._trace('post: r.read()')
        if response is None:
            raise EInvalidValue('expecting SOAP server response',
                                (host, post, action, soap_request))
        return response
    finally:
        try:
            if close_conn:
                conn._trace('pre.close()')
                conn.close()
                conn._trace('post.close()')
            else:
                conn._trace('keep open')
        except:
            pass
        pass
Example #21
0
 def _set_attr_value(self, token, v):
     if token == 'constant_value':
         type_v = type(v)
         if (not type_v == types.IntType) and (not type_v == types.LongType) \
            and (not type_v == types.FloatType) and (not type_v == types.StringType):
             raise EInvalidValue('constant_value', v,
                                 'bad type: %s' % str(type_v))
         self.bacnet_property.value = v
     elif (token == 'mode') or (token == 'property_reference'):
         raise EInvalidValue('token', token, \
                             'attempted to write a read-only property attribute')
     else:
         raise EInvalidValue('token', token, \
                             'Must be mode, constant_value, or property_reference')
     if self.is_client:  #make it write to the other device
         self.bacnet_property.set(self.parent.parent.instance
                                  )  # calls SOC_seq.as_tags() indirectly
Example #22
0
 def set(self, value, asyncOK=1):
     level = int(value)
     if level < 0 or level > 255:
         raise EInvalidValue('level', value,
                             "The level must be between 0 and 255")
     result = self._cbus.blocking_command("Sa=%s,g=%g,l=%s\n" %
                                          (self._app, self._grp, level))
     return
Example #23
0
 def as_protocol_name(self,protocol):
     try:
         return self._PROTOCOL_MAP[protocol.lower()]
     except KeyError:
         raise EInvalidValue('protocol',protocol,
                             "%r is not a supported protocol for %r" 
                             %(protocol,self.as_node_url())
                             )
Example #24
0
 def message_data(self, **overrides):
     keywords = self.keywords().copy()
     keywords.update(overrides)
     A2 = '%s:%s' % (keywords['method'], keywords['uri'])
     if keywords.has_key('qop'):
         if keywords['qop'] == 'auth':
             pass
         elif keywords['qop'] == 'auth-int':
             if not keywords.has_key('body_hash'):
                 raise EInvalidValue(
                     'body_hash', None, 'With qop == auth-int,'
                     ' a body_hash value must be passed in.')
             A2 = '%s:%s' % (A2, keywords['body_hash'])
         else:
             raise EInvalidValue('qop', keywords['qop'],
                                 'QOP value not recognized.')
     return A2
Example #25
0
 def as_input_node(self, reference):
     if reference in (None, '', u''):
         raise EInvalidValue('reference', reference, 'expected node URL')
     if reference == '$PARENT$':
         reference = '..'
     node = self.as_node(reference)
     if self.as_internal_node(reference) is self:
         raise ECircularReference(reference, self.name)
     return node
Example #26
0
def set_attribute(object, name, default, dictionary,
                  conversion=_no_conversion):
    if (dictionary.has_key(name) and 
        _string_to_token(dictionary[name], str) is not REQUIRED):
        try:
            value = _expand_properties(dictionary[name])
            value = _string_to_token(value,conversion)
        except Exception,e:
            raise EInvalidValue(name,dictionary[name])
Example #27
0
 def set_property(self, prop_name, prop_value):
     if not hasattr(self._test, prop_name):
         raise EInvalidValue(
                 'set_property',
                 prop_value,
                 'Error setting unknown property.'
             )
     setattr(self._test, prop_name, prop_value)
     return
Example #28
0
 def __init__(self, *args, **keywords):
     if (not args and not keywords) or (args and not keywords):
         self.from_list(args)
     elif keywords and not args:
         self.from_dictionary(keywords)
     else:
         raise EInvalidValue(
             'keywords', keywords, 'Alarm must be initialized with '
             'either keywords or args, not both.')
Example #29
0
 def setup_context(self):
     context = {}
     for variable in self.variables:
         name = variable['vn']
         definition = variable['node_reference']
         if context.has_key(name):
             raise EInvalidValue('variable', name, 'Duplicate name')
         context[name] = self.define_input(name, definition)
     return context
Example #30
0
 def __init__(self, *args, **keywords):
     if keywords.has_key('decode'):
         self.decode(keywords['decode'])
     elif len(args) == 1:
         self.encode(args[0])
     else:
         raise EInvalidValue('args',
                             args,
                             text='requires BDT table  or decode')