Python twisted.python.log 模块,err() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用twisted.python.log.err()

项目:FruityBot    作者:de-odex    | 项目源码 | 文件源码
def action(self, user, channel, msg):
        """Called when the bot sees someone do an action."""
        user = user.split('!', 1)[0]
        self.logic.log(colorama.Fore.MAGENTA + "* " + user + colorama.Fore.WHITE + " " + msg)
        if channel == self.nickname:
            f = self.logic.check_update(self.logic.FIRST_TIME_MSG, user, "firsttime.txt")
            u = self.logic.check_update(self.logic.UPDATE_MSG, user, "updates.txt")
            if f:
                self.msg(user, f)
            if u:
                self.msg(user, u)
            d = threads.deferToThread(self.logic.sendpp, msg, user, "np")
            d.addCallback(self.logCommand, user)
            d.addErrback(log.err)

        else:
            pass
项目:netwatch    作者:recourse    | 项目源码 | 文件源码
def lineReceived(self, line):
        self.resetTimeout()

        def processFailed(err):
            #if err.check(FTPCmdError):
            #    self.sendLine(err.value.response())
            #else:
            log.msg("Unexpected FTP error")
            log.err(err)

        def processSucceeded(result):
            if isinstance(result, tuple):
                self.reply(*result)
            elif result is not None:
                self.reply(result)

        d = defer.maybeDeferred(self.processCommand, line)
        d.addCallbacks(processSucceeded, processFailed)
        d.addErrback(log.err)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def logOn(self, chatui):
        """
        @returns: this breaks with L{interfaces.IAccount}
        @returntype: DeferredList of L{interfaces.IClient}s
        """
        # Overriding basesupport's implementation on account of the
        # fact that _startLogOn tends to return a deferredList rather
        # than a simple Deferred, and we need to do registerAccountClient.
        if (not self._isConnecting) and (not self._isOnline):
            self._isConnecting = 1
            d = self._startLogOn(chatui)
            d.addErrback(self._loginFailed)
            def registerMany(results):
                for success, result in results:
                    if success:
                        chatui.registerAccountClient(result)
                        self._cb_logOn(result)
                    else:
                        log.err(result)
            d.addCallback(registerMany)
            return d
        else:
            raise error.ConnectionError("Connection in progress")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _ebLogin(self, err, nickname):
        if err.check(ewords.AlreadyLoggedIn):
            self.privmsg(
                NICKSERV,
                nickname,
                "Already logged in.  No pod people allowed!")
        elif err.check(ecred.UnauthorizedLogin):
            self.privmsg(
                NICKSERV,
                nickname,
                "Login failed.  Goodbye.")
        else:
            log.msg("Unhandled error during login:")
            log.err(err)
            self.privmsg(
                NICKSERV,
                nickname,
                "Server error during login.  Sorry.")
        self.transport.loseConnection()


    # Great, now that's out of the way, here's some of the interesting
    # bits
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def setService(self, service):
        log.msg('setting client server to %s' % service)
        transport.SSHClientTransport.setService(self, service)
        if service.name != 'ssh-userauth' and self.factory.d:
            d = self.factory.d
            self.factory.d = None
            d.callback(None)
        if service.name == 'ssh-connection':
            # listen for UNIX
            if not self.factory.options['nocache']:
                user = self.factory.userAuthObject.user
                peer = self.transport.getPeer()
                filename = os.path.expanduser("~/.conch-%s-%s-%i" % (user, peer.host, peer.port))
                try:
                    u = unix.SSHUnixServerFactory(service)
                    try:
                        os.unlink(filename)
                    except OSError:
                        pass
                    self.unixServer = reactor.listenUNIX(filename, u, mode=0600, wantPID=1)
                except Exception, e:
                    log.msg('error trying to listen on %s' % filename)
                    log.err(e)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _cbRequestAvatarId(self, validKey, credentials):
        if not validKey:
            return failure.Failure(UnauthorizedLogin())
        if not credentials.signature:
            return failure.Failure(error.ValidPublicKey())
        else:
            try:
                pubKey = keys.getPublicKeyObject(data = credentials.blob)
                if keys.verifySignature(pubKey, credentials.signature,
                                        credentials.sigData):
                    return credentials.username
            except: # any error should be treated as a failed login
                f = failure.Failure()
                log.err()
                return f
        return failure.Failure(UnauthorizedLogin())
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connectionMade(self):
        self.transport.negotiationMap[NAWS] = self.telnet_NAWS
        self.transport.negotiationMap[LINEMODE] = self.telnet_LINEMODE

        for opt in (LINEMODE, NAWS, SGA):
            self.transport.do(opt).addErrback(log.err)
        for opt in (ECHO,):
            self.transport.will(opt).addErrback(log.err)

        self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)

        try:
            factory = self.factory
        except AttributeError:
            pass
        else:
            self.protocol.factory = factory

        self.protocol.makeConnection(self)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def renderFailure(self, failure, request):
        try:
            xml = request.d.toprettyxml()
        except:
            xml = ""
#         if not hasattr(request, 'channel'):
#             log.msg("The request got away from me before I could render an error page.")
#             log.err(failure)
#             return failure
        if not self.failed:
            self.failed = 1
            if failure:
                request.write("<html><head><title>%s: %s</title></head><body>\n" % (html.escape(str(failure.type)), html.escape(str(failure.value))))
            else:
                request.write("<html><head><title>Failure!</title></head><body>\n")
            utils.renderFailure(failure, request)
            request.write("<h3>Here is the partially processed DOM:</h3>")
            request.write("\n<pre>\n")
            request.write(html.escape(xml))
            request.write("\n</pre>\n")
            request.write("</body></html>")
            request.finish()
        return failure
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _authorize(self):
        # Authorization, (mostly) per the RFC
        try:
            authh = self.getHeader("Authorization")
            if not authh:
                self.user = self.password = ''
                return
            bas, upw = authh.split()
            if bas.lower() != "basic":
                raise ValueError
            upw = base64.decodestring(upw)
            self.user, self.password = upw.split(':', 1)
        except (binascii.Error, ValueError):
            self.user = self.password = ""
        except:
            log.err()
            self.user = self.password = ""
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def doRead(self):
        if self.writeBlockedOnRead:
            self.writeBlockedOnRead = 0
            self._resetReadWrite()
        try:
            return Connection.doRead(self)
        except SSL.ZeroReturnError:
            return main.CONNECTION_DONE
        except SSL.WantReadError:
            return
        except SSL.WantWriteError:
            self.readBlockedOnWrite = 1
            Connection.startWriting(self)
            Connection.stopReading(self)
            return
        except SSL.SysCallError, (retval, desc):
            if ((retval == -1 and desc == 'Unexpected EOF')
                or retval > 0):
                return main.CONNECTION_LOST
            log.err()
            return main.CONNECTION_LOST
        except SSL.Error, e:
            return e
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def failIfNotConnected(self, err):
        """
        Generic method called when the attemps to connect failed. It basically
        cleans everything it can: call connectionFailed, stop read and write,
        delete socket related members.
        """
        if (self.connected or self.disconnected or 
            not hasattr(self, "connector")):
            return

        self.connector.connectionFailed(failure.Failure(err))
        if hasattr(self, "reactor"):
            # this doesn't happen if we failed in __init__
            self.stopReading()
            self.stopWriting()
            del self.connector

        try:
            self._closeSocket()
        except AttributeError:
            pass
        else:
            del self.socket, self.fileno
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, host, port, bindAddress, connector, reactor=None):
        # BaseClient.__init__ is invoked later
        self.connector = connector
        self.addr = (host, port)

        whenDone = self.resolveAddress
        err = None
        skt = None

        try:
            skt = self.createInternetSocket()
        except socket.error, se:
            err = error.ConnectBindError(se[0], se[1])
            whenDone = None
        if whenDone and bindAddress is not None:
            try:
                skt.bind(bindAddress)
            except socket.error, se:
                err = error.ConnectBindError(se[0], se[1])
                whenDone = None
        self._finishInit(whenDone, skt, err, reactor)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connectionLost(self, reason):
        self.disconnected = True

        # Make sure to cleanup the other half
        _reader = self._reader
        _writer = self._writer
        protocol = self.protocol
        self._reader = self._writer = None
        self.protocol = None

        if _writer is not None and not _writer.disconnected:
            _writer.connectionLost(reason)

        if _reader is not None and not _reader.disconnected:
            _reader.connectionLost(reason)

        try:
            protocol.connectionLost(reason)
        except:
            log.err()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def reapProcess(self):
        """Try to reap a process (without blocking) via waitpid.

        This is called when sigchild is caught or a Process object loses its
        "connection" (stdout is closed) This ought to result in reaping all
        zombie processes, since it will be called twice as often as it needs
        to be.

        (Unfortunately, this is a slightly experimental approach, since
        UNIX has no way to be really sure that your process is going to
        go away w/o blocking.  I don't want to block.)
        """
        try:
            pid, status = os.waitpid(self.pid, os.WNOHANG)
        except:
            log.msg('Failed to reap %d:' % self.pid)
            log.err()
            pid = None
        if pid:
            self.processEnded(status)
            unregisterReapProcessHandler(pid, self)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def maybeCallProcessEnded(self):
        # two things must happen before we call the ProcessProtocol's
        # processEnded method. 1: the child process must die and be reaped
        # (which calls our own processEnded method). 2: the child must close
        # their stdin/stdout/stderr fds, causing the pty to close, causing
        # our connectionLost method to be called. #2 can also be triggered
        # by calling .loseConnection().
        if self.lostProcess == 2:
            try:
                exitCode = sig = None
                if self.status != -1:
                    if os.WIFEXITED(self.status):
                        exitCode = os.WEXITSTATUS(self.status)
                    else:
                        sig = os.WTERMSIG(self.status)
                else:
                    pass # wonder when this happens
                if exitCode or sig:
                    e = error.ProcessTerminated(exitCode, sig, self.status)
                else:
                    e = error.ProcessDone(self.status)
                self.proto.processEnded(failure.Failure(e))
                self.proto = None
            except:
                log.err()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def doRead(self):
        """Called when my socket is ready for reading."""
        read = 0
        while read < self.maxThroughput:
            try:
                data, addr = self.socket.recvfrom(self.maxPacketSize)
            except socket.error, se:
                no = se.args[0]
                if no in (EAGAIN, EINTR, EWOULDBLOCK):
                    return
                if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET):
                    if self._connectedAddr:
                        self.protocol.connectionRefused()
                else:
                    raise
            else:
                read += len(data)
                try:
                    self.protocol.datagramReceived(data, addr)
                except:
                    log.err()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _testImpl(self, method, expected, eb, exc=None):
        """
        Call the given remote method and attach the given errback to the
        resulting Deferred.  If C{exc} is not None, also assert that one
        exception of that type was logged.
        """
        rootDeferred = self.clientFactory.getRootObject()
        def gotRootObj(obj):
            failureDeferred = self._addFailingCallbacks(obj.callRemote(method), expected, eb)
            if exc is not None:
                def gotFailure(err):
                    self.assertEquals(len(self.flushLoggedErrors(exc)), 1)
                    return err
                failureDeferred.addBoth(gotFailure)
            return failureDeferred
        rootDeferred.addCallback(gotRootObj)
        return rootDeferred
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def testDeferredListWithAlreadyFiredDeferreds(self):
        # Create some deferreds, and err one, call the other
        d1 = defer.Deferred()
        d2 = defer.Deferred()
        d1.errback(GenericError('Bang'))
        d2.callback(2)

        # *Then* build the DeferredList
        dl = defer.DeferredList([d1, d2])

        result = []
        dl.addCallback(result.append)

        self.failUnlessEqual(1, len(result))

        d1.addErrback(lambda e: None)  # Swallow error
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _loadCredentials(self):
        try:
            f = file(self.filename)
        except:
            log.err()
            raise error.UnauthorizedLogin()
        else:
            for line in f:
                line = line.rstrip()
                parts = line.split(self.delim)

                if self.ufield >= len(parts) or self.pfield >= len(parts):
                    continue
                if self.caseSensitive:
                    yield parts[self.ufield], parts[self.pfield]
                else:
                    yield parts[self.ufield].lower(), parts[self.pfield]
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def ftp_PORT(self, address):
        addr = map(int, address.split(','))
        ip = '%d.%d.%d.%d' % tuple(addr[:4])
        port = addr[4] << 8 | addr[5]

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            self.cleanupDTP()

        self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)

        def connected(ignored):
            return ENTERING_PORT_MODE
        def connFailed(err):
            err.trap(PortConnectionError)
            return CANT_OPEN_DATA_CNX
        return self.dtpFactory.deferred.addCallbacks(connected, connFailed)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def handle_request(self, message, addr):
        # send immediate 100/trying message before processing
        #self.deliverResponse(self.responseFromRequest(100, message))
        f = getattr(self, "handle_%s_request" % message.method, None)
        if f is None:
            f = self.handle_request_default
        try:
            d = f(message, addr)
        except SIPError, e:
            self.deliverResponse(self.responseFromRequest(e.code, message))
        except:
            log.err()
            self.deliverResponse(self.responseFromRequest(500, message))
        else:
            if d is not None:
                d.addErrback(lambda e:
                    self.deliverResponse(self.responseFromRequest(e.code, message))
                )
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def login(self, message, host, port):
        parts = message.headers['authorization'][0].split(None, 1)
        a = self.authorizers.get(parts[0].lower())
        if a:
            try:
                c = a.decode(parts[1])
            except SIPError:
                raise
            except:
                log.err()
                self.deliverResponse(self.responseFromRequest(500, message))
            else:
                c.username += '@' + self.host
                self.portal.login(c, None, IContact
                    ).addCallback(self._cbLogin, message, host, port
                    ).addErrback(self._ebLogin, message, host, port
                    ).addErrback(log.err
                    )
        else:
            self.deliverResponse(self.responseFromRequest(501, message))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def do_RENAME(self, tag, oldname, newname):
        oldname, newname = [self._parseMbox(n) for n in oldname, newname]
        if oldname.lower() == 'inbox' or newname.lower() == 'inbox':
            self.sendNegativeResponse(tag, 'You cannot rename the inbox, or rename another mailbox to inbox.')
            return
        try:
            self.account.rename(oldname, newname)
        except TypeError:
            self.sendBadResponse(tag, 'Invalid command syntax')
        except MailboxException, m:
            self.sendNegativeResponse(tag, str(m))
        except:
            self.sendBadResponse(tag, "Server error encountered while renaming mailbox")
            log.err()
        else:
            self.sendPositiveResponse(tag, 'Mailbox renamed')
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _ebMX(self, failure, domain):
        from twisted.names import error, dns

        if self.fallbackToDomain:
            failure.trap(error.DNSNameError)
            log.msg("MX lookup failed; attempting to use hostname (%s) directly" % (domain,))

            # Alright, I admit, this is a bit icky.
            d = self.resolver.getHostByName(domain)
            def cbResolved(addr):
                return dns.Record_MX(name=addr)
            def ebResolved(err):
                err.trap(error.DNSNameError)
                raise DNSLookupError()
            d.addCallbacks(cbResolved, ebResolved)
            return d
        elif failure.check(error.DNSNameError):
            raise IOError("No MX found for %r" % (domain,))
        return failure
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def moveFileToNew(self):
        while True:
            newname = os.path.join(self.mbox.path, "new", _generateMaildirName())
            try:
                self.osrename(self.tmpname, newname)
                break
            except OSError, (err, estr):
                import errno
                # if the newname exists, retry with a new newname.
                if err != errno.EEXIST:
                    self.fail()
                    newname = None
                    break
        if newname is not None:
            self.mbox.list.append(newname)
            self.defer.callback(None)
            self.defer = None
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def undeleteMessages(self):
        """Undelete any deleted messages it is possible to undelete

        This moves any messages from .Trash/ subfolder back to their
        original position, and empties out the deleted dictionary.
        """
        for (real, trash) in self.deleted.items():
            try:
                os.rename(trash, real)
            except OSError, (err, estr):
                import errno
                # If the file has been deleted from disk, oh well!
                if err != errno.ENOENT:
                    raise
                # This is a pass
            else:
                try:
                    self.list[self.list.index(0)] = real
                except ValueError:
                    self.list.append(real)
        self.deleted.clear()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connectionLost(self, reason):
        # self.sendCode(421, 'Dropping connection.') # This does nothing...
        # Ideally, if we (rather than the other side) lose the connection,
        # we should be able to tell the other side that we are going away.
        # RFC-2821 requires that we try.
        if self.mode is DATA:
            try:
                for message in self.__messages:
                    try:
                        message.connectionLost()
                    except:
                        log.err()
                del self.__messages
            except AttributeError:
                pass
        if self._onLogout:
            self._onLogout()
            self._onLogout = None
        self.setTimeout(None)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, items, *args):
        AliasBase.__init__(self, *args)
        self.aliases = []
        while items:
            addr = items.pop().strip()
            if addr.startswith(':'):
                try:
                    f = file(addr[1:])
                except:
                    log.err("Invalid filename in alias file %r" % (addr[1:],))
                else:
                    addr = ' '.join([l.strip() for l in f])
                    items.extend(addr.split(','))
            elif addr.startswith('|'):
                self.aliases.append(ProcessAlias(addr[1:], *args))
            elif addr.startswith('/'):
                if os.path.isdir(addr):
                    log.err("Directory delivery not supported")
                else:
                    self.aliases.append(FileAlias(addr, *args))
            else:
                self.aliases.append(AddressAlias(addr, *args))
项目:slackbridge    作者:ocf    | 项目源码 | 文件源码
def check_slack_rtm(self):
        try:
            message_list = self.sc.rtm_read()
        except TimeoutError:
            log.err('Retrieving message from Slack RTM timed out')
            self.rtm_connect()
            return

        if not message_list:
            return

        for message in message_list:
            log.msg(message)

            if 'type' in message:
                message_obj = self.SlackMessage(message, self)
                self.message_queue.put(message_obj)
项目:p2pool-bch    作者:amarian12    | 项目源码 | 文件源码
def _think(self):
        try:
            if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
                (host, port), = self.node.get_good_peers(1)

                if self._host_to_ident(host) in self.attempts:
                    pass
                elif host in self.node.bans and self.node.bans[host] > time.time():
                    pass
                else:
                    #print 'Trying to connect to', host, port
                    reactor.connectTCP(host, port, self, timeout=5)
        except:
            log.err()

        return random.expovariate(1/1)
项目:p2pool-bch    作者:amarian12    | 项目源码 | 文件源码
def _think(self):
        try:
            if len(self.addr_store) < self.preferred_storage and self.peers:
                random.choice(self.peers.values()).send_getaddrs(count=8)
        except:
            log.err()

        return random.expovariate(1/20)
项目:p2pool-bch    作者:amarian12    | 项目源码 | 文件源码
def _send_work(self):
        try:
            x, got_response = self.wb.get_work(*self.wb.preprocess_request('' if self.username is None else self.username))
        except:
            log.err()
            self.transport.loseConnection()
            return
        jobid = str(random.randrange(2**128))
        self.other.svc_mining.rpc_set_difficulty(bitcoin_data.target_to_difficulty(x['share_target'])).addErrback(lambda err: None)
        self.other.svc_mining.rpc_notify(
            jobid, # jobid
            getwork._swap4(pack.IntType(256).pack(x['previous_block'])).encode('hex'), # prevhash
            x['coinb1'].encode('hex'), # coinb1
            x['coinb2'].encode('hex'), # coinb2
            [pack.IntType(256).pack(s).encode('hex') for s in x['merkle_link']['branch']], # merkle_branch
            getwork._swap4(pack.IntType(32).pack(x['version'])).encode('hex'), # version
            getwork._swap4(pack.IntType(32).pack(x['bits'].bits)).encode('hex'), # nbits
            getwork._swap4(pack.IntType(32).pack(x['timestamp'])).encode('hex'), # ntime
            True, # clean_jobs
        ).addErrback(lambda err: None)
        self.handler_map[jobid] = x, got_response
项目:telepresence    作者:datawire    | 项目源码 | 文件源码
def _done_parsing(self, host: str, port: int) -> None:
        """Called when the request is completely finished parsing."""
        if self.command == "CONNECT":
            d = self.connectClass(str(host), port, SOCKSv5Outgoing, self)
            d.addErrback(self._handle_error)
        elif self.command == "RESOLVE":

            def write_response(addr):
                self.write(b"\5\0\0\1" + socket.inet_aton(addr))
                self.transport.loseConnection()

            def write_error(e):
                log.err(e)
                self.write(b"\5\4\0\0")
                self.transport.loseConnection()

            self.reactor.resolve(
                host,
            ).addCallback(write_response).addErrback(write_error)
项目:bitmask-dev    作者:leapcode    | 项目源码 | 文件源码
def testExtractInvalidAttachedKey(self):
        KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..."

        message = MIMEMultipart()
        message.add_header("from", ADDRESS_2)
        key = MIMEApplication("", "pgp-keys")
        key.set_payload(KEY)
        message.attach(key)
        self.fetcher._keymanager.put_raw_key = Mock(
            return_value=defer.fail(KeyAddressMismatch()))

        def put_raw_key_called(_):
            self.fetcher._keymanager.put_raw_key.assert_called_once_with(
                KEY, address=ADDRESS_2)

        d = self._do_fetch(message.as_string())
        d.addCallback(put_raw_key_called)
        d.addErrback(log.err)
        return d
项目:bitmask-dev    作者:leapcode    | 项目源码 | 文件源码
def testFlagMessageOnBadJsonWhileDecrypting(self):
        doc = SoledadDocument()
        doc.doc_id = '1'
        doc.content = {'_enc_json': ''}

        err = ValueError('No JSON object could be decoded')

        def assert_failure():
            mock_logger_error.assert_any_call(
                'Error while decrypting 1')
            mock_logger_error.assert_any_call(
                'No JSON object could be decoded')
            self.assertEquals(doc.content['errdecr'], True)

        with patch.object(Logger, 'error') as mock_logger_error:
            with patch.object(utils, 'json_loads') as mock_json_loader:
                self.fetcher._update_incoming_message = Mock()
                mock_json_loader.side_effect = err

                self.fetcher._process_decrypted_doc(doc, '')

                assert_failure()
项目:p2pool-unitus    作者:amarian12    | 项目源码 | 文件源码
def _think(self):
        try:
            if len(self.conns) < self.desired_conns and len(self.attempts) < self.max_attempts and self.node.addr_store:
                (host, port), = self.node.get_good_peers(1)

                if self._host_to_ident(host) in self.attempts:
                    pass
                elif host in self.node.bans and self.node.bans[host] > time.time():
                    pass
                else:
                    #print 'Trying to connect to', host, port
                    reactor.connectTCP(host, port, self, timeout=5)
        except:
            log.err()

        return random.expovariate(1/1)
项目:p2pool-unitus    作者:amarian12    | 项目源码 | 文件源码
def _send_work(self):
        try:
            x, got_response = self.wb.get_work(*self.wb.preprocess_request('' if self.username is None else self.username))
        except:
            log.err()
            self.transport.loseConnection()
            return
        jobid = str(random.randrange(2**128))
        self.other.svc_mining.rpc_set_difficulty(bitcoin_data.target_to_difficulty(x['share_target'])*self.diff_multiplier).addErrback(lambda err: None)
        self.other.svc_mining.rpc_notify(
            jobid, # jobid
            getwork._swap4(pack.IntType(256).pack(x['previous_block'])).encode('hex'), # prevhash
            x['coinb1'].encode('hex'), # coinb1
            x['coinb2'].encode('hex'), # coinb2
            [pack.IntType(256).pack(s).encode('hex') for s in x['merkle_link']['branch']], # merkle_branch
            getwork._swap4(pack.IntType(32).pack(x['version'])).encode('hex'), # version
            getwork._swap4(pack.IntType(32).pack(x['bits'].bits)).encode('hex'), # nbits
            getwork._swap4(pack.IntType(32).pack(x['timestamp'])).encode('hex'), # ntime
            True, # clean_jobs
        ).addErrback(lambda err: None)
        self.handler_map[jobid] = x, got_response
项目:PGO-mapscan-opt    作者:seikur0    | 项目源码 | 文件源码
def shutdown(seconds, result=None):
    if not isinstance(seconds, numbers.Number):
        log.err(seconds)
        seconds = 1
    d = Deferred()
    d.addCallback(stop_reaktor)
    reactor.callLater(seconds, d.callback, result)
    return d
项目:farfetchd    作者:isislovecruft    | 项目源码 | 文件源码
def getCaptchaImage(self, request):
        """Get a random CAPTCHA image from our **captchaDir**.

        Creates a :class:`~farfetchd.captcha.GimpCaptcha`, and calls its
        :meth:`~farfetchd.captcha.GimpCaptcha.get` method to return a random
        CAPTCHA and challenge string.

        :type request: :api:`twisted.web.http.Request`
        :param request: A client's initial request for some other resource
            which is protected by this one (i.e. protected by a CAPTCHA).
        :returns: A 2-tuple of ``(image, challenge)``, where::
            - ``image`` is a string holding a binary, JPEG-encoded image.
            - ``challenge`` is a unique string associated with the request.
        """
        # Create a new HMAC key, specific to requests from this client:
        clientIP = self.getClientIP(request)
        clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP)
        capt = captcha.GimpCaptcha(self.publicKey, self.secretKey,
                                   clientHMACKey, self.captchaDir)
        try:
            capt.get()
        except captcha.GimpCaptchaError as error:
            log.msg(error)
        except Exception as error:  # pragma: no cover
            log.err("Unhandled error while retrieving Gimp captcha!")
            log.err(error)

        return (capt.image, capt.challenge)
项目:farfetchd    作者:isislovecruft    | 项目源码 | 文件源码
def render_GET(self, request):
        """Retrieve a ReCaptcha from the API server and serve it to the client.

        :type request: :api:`twisted.web.http.Request`
        :param request: A ``Request`` object for a CAPTCHA.
        :rtype: str
        :returns: A JSON blob containing the following fields:
             * "version": The Farfetchd protocol version.
             * "image": A base64-encoded CAPTCHA JPEG image.
             * "challenge": A base64-encoded, encrypted challenge.  The client
               will need to hold on to the and pass it back later, along with
               their challenge response.
             * "error": An ASCII error message.
            Any of the above JSON fields may be "null".
        """
        image, challenge = self.getCaptchaImage(request)

        json = {
            'data': {
                'id': 1,
                'type': self.responseType,
                'version': FARFETCHD_API_VERSION,
                'image': image,
                'challenge': challenge, # The challenge is already base64-encoded
            }
        }

        try:
            json["data"]["image"] = base64.b64encode(image)
        except Exception as err:
            log.err("Could not construct or encode captcha!")
            log.err(err)

        return self.formatResponse(json, request)
项目:farfetchd    作者:isislovecruft    | 项目源码 | 文件源码
def checkSolution(self, request):
        """Process a solved CAPTCHA via
        :meth:`farfetchd.captcha.GimpCaptcha.check`.

        :type request: :api:`twisted.web.http.Request`
        :param request: A ``Request`` object, including POST arguments which
            should include two key/value pairs: one key being
            ``'captcha_challenge_field'``, and the other,
            ``'captcha_response_field'``. These POST arguments should be
            obtained from :meth:`render_GET`.
        :rtupe: bool
        :returns: True, if the CAPTCHA solution was valid; False otherwise.
        """
        valid = False

        try:
            challenge, solution = self.extractClientSolution(request)
        except Exception as err:
            log.err(err)
            return self.failureResponse(request)

        clientIP = self.getClientIP(request)
        clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP)

        try:
            valid = captcha.GimpCaptcha.check(challenge, solution,
                                              self.secretKey, clientHMACKey)
        except captcha.CaptchaExpired as error:
            log.error(error)
            valid = False

        log.msg("%sorrect captcha from %r: %r."
                % ("C" if valid else "Inc", clientIP, solution))
        return valid
项目:farfetchd    作者:isislovecruft    | 项目源码 | 文件源码
def render_POST(self, request):
        """Process a client's CAPTCHA solution.

        If the client's CAPTCHA solution is valid (according to
        :meth:`checkSolution`), process and serve their original
        request. Otherwise, redirect them back to a new CAPTCHA page.

        :type request: :api:`twisted.web.http.Request`
        :param request: A ``Request`` object, including POST arguments which
            should include two key/value pairs: one key being
            ``'captcha_challenge_field'``, and the other,
            ``'captcha_response_field'``. These POST arguments should be
            obtained from :meth:`render_GET`.
        :rtype: str
        :returns: A rendered HTML page containing a ReCaptcha challenge image
            for the client to solve.
        """
        data = {
            "data": {
                "id": 3,
                "type": self.responseType,
                "version": FARFETCHD_API_VERSION,
                "result": False,
            }
        }

        try:
            if self.checkSolution(request) is True:
                data["data"]["result"] = True
                return self.formatResponse(data, request)
            else:
                return self.failureResponse(request)
        except Exception as err:
            log.err(err)


#class FarfetchdRequestHandler(http.Request):
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _ebUserCall(self, err, p):
        return failure.Failure(Exception(p, err))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _cbUserCall(self, results):
        for (success, result) in results:
            if not success:
                user, err = result.value # XXX
                self.remove(user, err.getErrorMessage())
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_MODE(self, prefix, params):
        """User mode message

        Parameters: <nickname>
        *( ( "+" / "-" ) *( "i" / "w" / "o" / "O" / "r" ) )

        """
        try:
            channelOrUser = params[0].decode(self.encoding)
        except UnicodeDecodeError:
            self.sendMessage(
                irc.ERR_NOSUCHNICK, params[0],
                ":No such nickname (could not decode your unicode!)")
            return

        if channelOrUser.startswith('#'):
            def ebGroup(err):
                err.trap(ewords.NoSuchGroup)
                self.sendMessage(
                    irc.ERR_NOSUCHCHANNEL, params[0],
                    ":That channel doesn't exist.")
            d = self.realm.lookupGroup(channelOrUser[1:])
            d.addCallbacks(
                self._channelMode,
                ebGroup,
                callbackArgs=tuple(params[1:]))
        else:
            def ebUser(err):
                self.sendMessage(
                    irc.ERR_NOSUCHNICK,
                    ":No such nickname.")

            d = self.realm.lookupUser(channelOrUser)
            d.addCallbacks(
                self._userMode,
                ebUser,
                callbackArgs=tuple(params[1:]))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_JOIN(self, prefix, params):
        """Join message

        Parameters: ( <channel> *( "," <channel> ) [ <key> *( "," <key> ) ] )
        """
        try:
            groupName = params[0].decode(self.encoding)
        except UnicodeDecodeError:
            self.sendMessage(
                irc.IRC_NOSUCHCHANNEL, params[0],
                ":No such channel (could not decode your unicode!)")
            return

        if groupName.startswith('#'):
            groupName = groupName[1:]

        def cbGroup(group):
            def cbJoin(ign):
                self.userJoined(group, self)
                self.names(
                    self.name,
                    '#' + group.name,
                    [user.name for user in group.iterusers()])
                self._sendTopic(group)
            return self.avatar.join(group).addCallback(cbJoin)

        def ebGroup(err):
            self.sendMessage(
                irc.ERR_NOSUCHCHANNEL, '#' + groupName,
                ":No such channel.")

        self.realm.getGroup(groupName).addCallbacks(cbGroup, ebGroup)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_PART(self, prefix, params):
        """Part message

        Parameters: <channel> *( "," <channel> ) [ <Part Message> ]
        """
        try:
            groupName = params[0].decode(self.encoding)
        except UnicodeDecodeError:
            self.sendMessage(
                irc.ERR_NOTONCHANNEL, params[0],
                ":Could not decode your unicode!")
            return

        if groupName.startswith('#'):
            groupName = groupName[1:]

        if len(params) > 1:
            reason = params[1].decode('utf-8')
        else:
            reason = None

        def cbGroup(group):
            def cbLeave(result):
                self.userLeft(group, self, reason)
            return self.avatar.leave(group, reason).addCallback(cbLeave)

        def ebGroup(err):
            err.trap(ewords.NoSuchGroup)
            self.sendMessage(
                irc.ERR_NOTONCHANNEL,
                '#' + groupName,
                ":" + err.getErrorMessage())

        self.realm.lookupGroup(groupName).addCallbacks(cbGroup, ebGroup)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def irc_NAMES(self, prefix, params):
        """Names message

        Parameters: [ <channel> *( "," <channel> ) [ <target> ] ]
        """
        #<< NAMES #python
        #>> :benford.openprojects.net 353 glyph = #python :Orban ... @glyph ... Zymurgy skreech
        #>> :benford.openprojects.net 366 glyph #python :End of /NAMES list.
        try:
            channel = params[-1].decode(self.encoding)
        except UnicodeDecodeError:
            self.sendMessage(
                irc.ERR_NOSUCHCHANNEL, params[-1],
                ":No such channel (could not decode your unicode!)")
            return

        if channel.startswith('#'):
            channel = channel[1:]

        def cbGroup(group):
            self.names(
                self.name,
                '#' + group.name,
                [user.name for user in group.iterusers()])

        def ebGroup(err):
            err.trap(ewords.NoSuchGroup)
            # No group?  Fine, no names!
            self.names(
                self.name,
                '#' + channel,
                [])

        self.realm.lookupGroup(channel).addCallbacks(cbGroup, ebGroup)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _getTopic(self, channel):
        #<< TOPIC #python
        #>> :benford.openprojects.net 332 glyph #python :<churchr> I really did. I sprained all my toes.
        #>> :benford.openprojects.net 333 glyph #python itamar|nyc 994713482
        def ebGroup(err):
            err.trap(ewords.NoSuchGroup)
            self.sendMessage(
                irc.ERR_NOSUCHCHANNEL, '=', channel,
                ":That channel doesn't exist.")

        self.realm.lookupGroup(channel).addCallbacks(self._sendTopic, ebGroup)