Use SSDP as described by the Philips guide
506400
def via_upnp():
    
    ssdp_list = ssdp_discover("ssdp:all", timeout=5)
    #import pickle
    #with open("ssdp.pickle", "wb") as f:
        #pickle.dump(ssdp_list,f)
    bridges_from_ssdp = [u for u in ssdp_list if 'IpBridge' in u.server]
    logger.info('SSDP returned %d items with %d Hue bridges(s).',
                 len(ssdp_list), len(bridges_from_ssdp))
    # Confirm SSDP gave an accessible bridge device by reading from the returned
    # location.  Should look like: http://192.168.0.1:80/description.xml
    found_bridges = {}
    for bridge in bridges_from_ssdp:
        serial, bridge_info = parse_description_xml(bridge.location)
        if serial:
            found_bridges[serial] = bridge_info

    logger.debug('%s', found_bridges)
    if found_bridges:
        return found_bridges
    else:
        raise DiscoveryError('SSDP returned nothing')
1308177
def work(self):
        
        self.do_print = True
        if self.args.old:
            self.switch_fingerprint_method(True)

        ret = self.process_inputs()

        if self.args.dump:
            self.dump(ret)

        logger.info('### SUMMARY ####################')
        logger.info('Records tested: %s' % self.tested)
        logger.info('.. PEM certs: . . . %s' % self.num_pem_certs)
        logger.info('.. DER certs: . . . %s' % self.num_der_certs)
        logger.info('.. RSA key files: . %s' % self.num_rsa_keys)
        logger.info('.. PGP master keys: %s' % self.num_pgp_masters)
        logger.info('.. PGP total keys:  %s' % self.num_pgp_total)
        logger.info('.. SSH keys:  . . . %s' % self.num_ssh)
        logger.info('.. APK keys:  . . . %s' % self.num_apk)
        logger.info('.. JSON keys: . . . %s' % self.num_json)
        logger.info('.. LDIFF certs: . . %s' % self.num_ldiff_cert)
        logger.info('.. JKS certs: . . . %s' % self.num_jks_cert)
        logger.info('.. PKCS7: . . . . . %s' % self.num_pkcs7_cert)
        logger.debug('. Total RSA keys . %s  (# of keys RSA extracted & analyzed)' % self.num_rsa)
        if self.found > 0:
            logger.info('Fingerprinted keys found: %s' % self.found)
            logger.info('WARNING: Potential vulnerability')
        else:
            logger.info('No fingerprinted keys found (OK)')
        logger.info('################################')
983944
def keypair_setup():
  """"""

  os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)

  keypair_name = u.get_keypair_name()
  keypair = u.get_keypair_dict().get(keypair_name, None)
  keypair_fn = u.get_keypair_fn()
  if keypair:
    print("Reusing keypair " + keypair_name)
    # check that local pem file exists and is readable
    assert os.path.exists(
      keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % (
      keypair_name, keypair_fn, keypair_name)
    keypair_contents = open(keypair_fn).read()
    assert len(keypair_contents) > 0
  else:
    print("Creating keypair " + keypair_name)
    ec2 = u.get_ec2_resource()
    assert not os.path.exists(
      keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % (
      keypair_fn)
    keypair = ec2.create_key_pair(KeyName=keypair_name)

    open(keypair_fn, 'w').write(keypair.key_material)
    os.system('chmod 400 ' + keypair_fn)

  return keypair
888821
def make_sshable(c):
    
    user = c.travis.sudo.user
    home = "~{0}".format(user)
    # Run sudo() as the new sudo user; means less chown'ing, etc.
    c.config.sudo.user = user
    ssh_dir = "{0}/.ssh".format(home)
    # TODO: worth wrapping in 'sh -c' and using '&&' instead of doing this?
    for cmd in ("mkdir {0}", "chmod 0700 {0}"):
        c.sudo(cmd.format(ssh_dir, user))
    c.sudo('ssh-keygen -f {0}/id_rsa -N ""'.format(ssh_dir))
    c.sudo("cp {0}/{{id_rsa.pub,authorized_keys}}".format(ssh_dir))
1062584
def pbm(self):
        
        if not self.disable_rpyc:
            from plumbum import SshMachine
            return SshMachine(host=self.private_hostname, user=self.username,
                              keyfile=self.key_filename,
                              ssh_opts=["-o", "UserKnownHostsFile=/dev/null",
                                        "-o", "StrictHostKeyChecking=no"])
        else:
            return None
1363674
def discover_upnp_devices(
        self, st="upnp:rootdevice", timeout=2, mx=1, retries=1
    ):
        
        # prepare UDP socket to transfer the SSDP packets
        s = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
        )
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        s.settimeout(timeout)

        # prepare SSDP discover message
        msg = SSDPDiscoveryMessage(mx=mx, st=st)

        # try to get devices with multiple retries in case of failure
        devices = {}
        for _ in range(retries):
            # send SSDP discovery message
            s.sendto(msg.bytes, SSDP_MULTICAST_ADDR)

            devices = {}
            try:
                while True:
                    # parse response and store it in dict
                    r = SSDPResponse(s.recvfrom(65507))
                    devices[r.usn] = r

            except socket.timeout:
                break

        return devices
1125176
def normalize_cert_dir():
    '''
        
    '''
    current_cn = get_crt_common_name()

    if not os.path.isdir(COZY_CONFIG_PATH):
        print 'Need to create {}'.format(COZY_CONFIG_PATH)
        os.mkdir(COZY_CONFIG_PATH, 0755)

    if not os.path.isdir(CERTIFICATES_PATH):
        print 'Need to create {}'.format(CERTIFICATES_PATH)
        os.mkdir(CERTIFICATES_PATH, 0755)

    if not os.path.isdir(ACME_PRIVATE_PATH):
        print 'Need to create {}'.format(ACME_PRIVATE_PATH)
        os.mkdir(ACME_PRIVATE_PATH, 0700)

    if os.path.isfile(OLD_CERTIFICATE_PATH) and \
            not os.path.islink(OLD_CERTIFICATE_PATH):
        target = '{}/{}.crt'.format(CERTIFICATES_PATH, current_cn)
        print 'Move {} to {}'.format(CERTIFICATES_PATH, target)
        os.rename(OLD_CERTIFICATE_PATH, target)
    else:
        print 'Nothing to do for {}'.format(OLD_CERTIFICATE_PATH)

    if os.path.isfile(OLD_PRIVATE_KEY_PATH) and \
            not os.path.islink(OLD_PRIVATE_KEY_PATH):
        target = '{}/{}.key'.format(CERTIFICATES_PATH, current_cn)
        print 'Move {} to {}'.format(OLD_PRIVATE_KEY_PATH, target)
        os.rename(OLD_PRIVATE_KEY_PATH, target)
    else:
        print 'Nothing to do for {}'.format(OLD_PRIVATE_KEY_PATH)

    if current_cn:
        make_links(current_cn)
330050
def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None):
    
    store = _SSHStore(host, maildir)
    _pull(store, localmaildir, noop, verbose, filterfile)
871215
def _setup_ssh(self):
        """"""
        global paramiko
        if paramiko is none:
            import paramiko

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
1190888
def activatePdpContextRequest(AccessPointName_presence=0,
                              ProtocolConfigurationOptions_presence=0):
    """"""
    a = TpPd(pd=0x8)
    b = MessageType(mesType=0x41)  # 01000001
    c = NetworkServiceAccessPointIdentifier()
    d = LlcServiceAccessPointIdentifier()
    e = QualityOfService()
    f = PacketDataProtocolAddress()
    packet = a / b / c / d / e / f
    if AccessPointName_presence is 1:
        g = AccessPointName(ieiAPN=0x28)
        packet = packet / g
    if ProtocolConfigurationOptions_presence is 1:
        h = ProtocolConfigurationOptions(ieiPCO=0x27)
        packet = packet / h
    return packet
525435
def _setup_transport(self):
        """"""
        if hasattr(self, 'sslopts'):
            self.sock = ssl.wrap_socket(self.sock, **self.sslopts)
        else:
            self.sock = ssl.wrap_socket(self.sock)
        self.sock.do_handshake()
        self._quick_recv = self.sock.read
108960
def cli(env, **args):
    """"""
    mgr = SoftLayer.HardwareManager(env.client)

    # Get the SSH keys
    ssh_keys = []
    for key in args.get('key'):
        resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
        key_id = helpers.resolve_id(resolver, key, 'SshKey')
        ssh_keys.append(key_id)

    order = {
        'hostname': args['hostname'],
        'domain': args['domain'],
        'size': args['size'],
        'location': args.get('datacenter'),
        'ssh_keys': ssh_keys,
        'post_uri': args.get('postinstall'),
        'os': args['os'],
        'hourly': args.get('billing') == 'hourly',
        'port_speed': args.get('port_speed'),
        'no_public': args.get('no_public') or False,
        'extras': args.get('extra'),
    }

    # Do not create hardware server with --test or --export
    do_create = not (args['export'] or args['test'])

    output = None
    if args.get('test'):
        result = mgr.verify_order(**order)

        table = formatting.Table(['Item', 'cost'])
        table.align['Item'] = 'r'
        table.align['cost'] = 'r'

        total = 0.0
        for price in result['prices']:
            total += float(price.get('recurringFee', 0.0))
            rate = "%.2f" % float(price['recurringFee'])

            table.add_row([price['item']['description'], rate])

        table.add_row(['Total monthly cost', "%.2f" % total])
        output = []
        output.append(table)
        output.append(formatting.FormattedItem(
            '',
            ' -- ! Prices reflected here are retail and do not '
            'take account level discounts and are not guaranteed.'))

    if args['export']:
        export_file = args.pop('export')
        template.export_to_template(export_file, args,
                                    exclude=['wait', 'test'])
        env.fout('Successfully exported options to a template file.')
        return

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. "
                "Continue?")):
            raise exceptions.CLIAbort('Aborting dedicated server order.')

        result = mgr.place_order(**order)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', result['orderId']])
        table.add_row(['created', result['orderDate']])
        output = table

    env.fout(output)
959564
def run_agent(device_type):
    """"""
    p = argparse.ArgumentParser()
    p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
    p.add_argument('-v', '--verbose', default=0, action='count')
    p.add_argument('--server', default=False, action='store_true',
                   help='Use stdin/stdout for communication with GPG.')

    p.add_argument('--pin-entry-binary', type=str, default='pinentry',
                   help='Path to PIN entry UI helper.')
    p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
                   help='Path to passphrase entry UI helper.')
    p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
                   help='Expire passphrase from cache after this duration.')

    args, _ = p.parse_known_args()

    assert args.homedir

    log_file = os.path.join(args.homedir, 'gpg-agent.log')
    util.setup_logging(verbosity=args.verbose, filename=log_file)

    log.debug('sys.argv: %s', sys.argv)
    log.debug('os.environ: %s', os.environ)
    log.debug('pid: %d, parent pid: %d', os.getpid(), os.getppid())
    try:
        env = {'GNUPGHOME': args.homedir, 'PATH': os.environ['PATH']}
        pubkey_bytes = keyring.export_public_keys(env=env)
        device_type.ui = device.ui.UI(device_type=device_type,
                                      config=vars(args))
        device_type.ui.cached_passphrase_ack = util.ExpiringCache(
            seconds=float(args.cache_expiry_seconds))
        handler = agent.Handler(device=device_type(),
                                pubkey_bytes=pubkey_bytes)

        sock_server = _server_from_assuan_fd(os.environ)
        if sock_server is None:
            sock_server = _server_from_sock_path(env)

        with sock_server as sock:
            for conn in agent.yield_connections(sock):
                with contextlib.closing(conn):
                    try:
                        handler.handle(conn)
                    except agent.AgentStop:
                        log.info('stopping gpg-agent')
                        return
                    except IOError as e:
                        log.info('connection closed: %s', e)
                        return
                    except Exception as e:  # pylint: disable=broad-except
                        log.exception('handler failed: %s', e)

    except Exception as e:  # pylint: disable=broad-except
        log.exception('gpg-agent failed: %s', e)
1267860
def i2m(self, pkt, p):
        
        cur = b""
        if isinstance(p, _GenericTLSSessionInheritance):
            if pkt.type is None:
                if isinstance(p, TLSChangeCipherSpec):
                    pkt.type = 20
                elif isinstance(p, TLSAlert):
                    pkt.type = 21
                elif isinstance(p, _TLSHandshake):
                    pkt.type = 22
                elif isinstance(p, TLSApplicationData):
                    pkt.type = 23
            p.tls_session = pkt.tls_session
            if not pkt.tls_session.frozen:
                cur = p.raw_stateful()
                p.post_build_tls_session_update(cur)
            else:
                cur = raw(p)
        else:
            pkt.type = 23
            cur = raw(p)
        return cur
190178
def discover(timeout=1, retries=1):
    
    locations = []

    group = ('239.255.255.250', 1900)
    service = 'ssdp:urn:schemas-upnp-org:device:MediaRenderer:1'  # 'ssdp:all'
    message = '\r\n'.join(['M-SEARCH * HTTP/1.1',
                           'HOST: {group[0]}:{group[1]}',
                           'MAN: "ssdp:discover"',
                           'ST: {st}',
                           'MX: 1', '', '']).format(group=group, st=service)

    socket.setdefaulttimeout(timeout)
    for _ in range(retries):
        sock = socket.socket(socket.AF_INET,
                             socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        # socket options
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

        # send group multicast
        sock.sendto(message.encode('utf-8'), group)

        while True:
            try:
                response = sock.recv(2048).decode('utf-8')
                for line in response.split('\r\n'):
                    if line.startswith('Location: '):
                        location = line.split(' ')[1].strip()
                        if not location in locations:
                            locations.append(location)
            except socket.timeout:
                break
    devices = [RaumfeldDevice(location) for location in locations]

    # only return 'Virtual Media Player' and sort the list
    return sorted([device for device in devices
                   if device.model_description == 'Virtual Media Player'],
                  key=lambda device: device.friendly_name)
952295
function DiscoveryClientSSDP(app) {
  app.properties[SERVER.Capabilities][THISMIDDLEWARE.CAPABILITY] = {};
  app.properties[SERVER.Capabilities][THISMIDDLEWARE.CAPABILITY][SERVER.Version] = packageVersion;

  //Also register as standard IOPA DISCOVERY SERVER MIDDLEWARE
  app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.DiscoveryServer] = {};
  app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.DiscoveryServer][SERVER.Version] = app.properties[SERVER.Capabilities][IOPA.CAPABILITIES.App][SERVER.Version];

  this._seq = 0;
  this._factory = new iopa.Factory();
  this._SSDPserver = null;
  this._SSDPclient = null;
  this._HTTPClient = null;
  
  this.id = app.properties[SERVER.AppId] + ":";
  this.seq = 0;

  app.device = app.device || {};
  app.device.probe = this.probe.bind(this, app.device.probe || function(query, cb){return Promise.resolve(null);});
  
  this.ssdpApp = new iopa.App();
  this.ssdpApp.use(IopaUDP);
  this.ssdpApp.use(IopaSSDP);
  this.ssdpApp.use(IopaCache.Match);
    this.ssdpApp.use(IopaCache.Cache);
 this.ssdpApp.use(IopaMessageLogger);

 
  this.ssdpApp.use(this.invoke.bind(this));
  
}
1211221
def step1(self, pin):
        """"""
        context = SRPContext(
            'Pair-Setup', str(pin),
            prime=constants.PRIME_3072,
            generator=constants.PRIME_3072_GEN,
            hash_func=hashlib.sha512)
        self._session = SRPClientSession(
            context, binascii.hexlify(self._auth_private).decode())