Пример #1
0
    async def start(self):
        pCreationFlags = 0

        startupInfo = None
        if platform.system() == 'Windows':
            startupInfo = subprocess.STARTUPINFO()
            startupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupInfo.wShowWindow = subprocess.SW_HIDE

        portMin = cParentGet('socksPortRange.minimum')
        portMax = cParentGet('socksPortRange.maximum')

        for socksPort in range(portMin, portMax):
            self.torCfg.socksPort = socksPort

            await asyncWriteFile(self.configPath, str(self.torCfg), 'w+t')

            args = [self.torPath, '-f', self.configPath]
            log.debug(f'Starting TOR with args: {args}')

            try:
                f = self.loop.subprocess_exec(lambda: self.torProto,
                                              *args,
                                              stdout=asyncio.subprocess.PIPE,
                                              stderr=asyncio.subprocess.PIPE,
                                              startupinfo=startupInfo,
                                              creationflags=pCreationFlags)

                self.transport, self.proto = await f

                self._procPid = self.transport.get_pid()
                self.process = psutil.Process(self._procPid)

                # Wait a bit, if there are port binding issues
                # tor will exit immediately
                await asyncio.sleep(3)

                status = self.process.status()
                assert status in [
                    psutil.STATUS_RUNNING, psutil.STATUS_SLEEPING
                ]
            except Exception as err:
                log.debug(f'Starting TOR failed on port {socksPort} : '
                          f'error {err}')
                self._procPid, self.process = None, None
                self.transport.close()
                continue
            else:
                if 0:
                    self.torController = TorController(
                        self.torCfg.controlPort, self.torCfg._controlPass)

                log.debug(f'Starting TOR: OK on port {socksPort}')
                return True

        return False
Пример #2
0
    def config(self):
        base = super().config()
        jsonConfig = cParentGet('serviceTypes.json')

        if jsonConfig:
            return configMerge(base, jsonConfig)

        return base
Пример #3
0
    def configApply(self):
        mode = cParentGet('unixfs.directoryView.mode')
        if mode == 'list':
            self.viewModeList()
        elif mode == 'icon':
            self.viewModeIcon()

        self.setIconSize(self.iconSize)
Пример #4
0
    async def storeWelcome(self):
        contact = await database.bmContactByNameFirst('galacteek-support')

        if not contact:
            # not found
            return

        body = cParentGet('messages.welcome.body')
        subject = cParentGet('messages.welcome.subject')

        msg = EmailMessage()
        msg['From'] = f'{contact.bmAddress}@bitmessage'
        msg['To'] = f'{self.bmAddress}@bitmessage'
        msg['Subject'] = subject

        msg.set_payload(body.format(bmAddress=self.bmAddress))

        await self.store(msg)
Пример #5
0
    async def on_start(self) -> None:
        await super().on_start()

        if self.app.windowsSystem:
            log.debug('Bitmessage service not yet supported on this platform')
            return

        if not cParentGet('enabled'):
            log.debug('Bitmessage service is not enabled')
            return

        log.debug('Starting bitmessage client')

        self.rootPath.mkdir(parents=True, exist_ok=True)
        self.mailDirPath.mkdir(parents=True, exist_ok=True)
        self.notBitDataPath.mkdir(parents=True, exist_ok=True)
        self.mailBoxesPath.mkdir(parents=True, exist_ok=True)

        await self.importBmContacts()

        await self.add_runtime_dependency(self.mailer)

        if self.which(NOTBIT):
            self.notbitProcess = NotBitProcess(
                self.notBitDataPath,
                self.mailDirPath,
                listenPort=cParentGet('notbit.listenPort'),
                useTor=cParentGet('notbit.useTor'))
            self.notbitProcess.nbProtocol.sPowCalculated.connectTo(
                self.onPowCalculated)
            self.notbitProcess.nbProtocol.sMessageAccepted.connectTo(
                self.onMessageAccepted)
            if await self.notbitProcess.start():
                await self.psPublish({
                    'type': 'ServiceStarted',
                    'event': {
                        'servicePort': self.notbitProcess.listenPort
                    }
                })
        else:
            log.debug('Notbit could not be found, not starting process')
Пример #6
0
    async def importBmContacts(self):
        contacts = cParentGet('bmCoreContacts')

        if not contacts:
            return

        for contact in contacts:
            log.debug(f'Storing contact {contact}')

            await database.bmContactAdd(contact.get('address'),
                                        contact.get('name'),
                                        groupName=contact.get('group'))
Пример #7
0
async def getPageResults(query, page, filters={}, sslverify=True,
                         proxyUrl=None,
                         timeout=None):
    timeout = cParentGet('search.ipfsSearch.pageResultsTimeout')
    try:
        with async_timeout.timeout(timeout):
            results = await searchPage(query, page, filters=filters,
                                       proxyUrl=proxyUrl,
                                       sslverify=sslverify)
            return IPFSSearchResults(page, results)
    except Exception as err:
        log.debug(f'ipfs-search error ({query}, page {page}): {err}')
        return emptyResults
Пример #8
0
    async def startProcess(self):
        if cParentGet('notbit.objects.purgeOnStartup') is True:
            log.debug(f'Purging objects cache: {self.objectsPath}')

            await asyncRmTree(str(self.objectsPath))

        if self.pidFilePath.is_file():
            # TODO: move to ProcessLauncher

            log.debug(f'PID file {self.pidFilePath} exists, checking process')

            text = await asyncReadFile(str(self.pidFilePath), mode='rt')
            try:
                pid = int(text.split('\n').pop(0))
                prevProc = Process(pid)
                prevProc.terminate()
            except Exception as err:
                log.debug(f'Invalid PID file {self.pidFilePath}: {err}')

            self.removePidFile()

        if self.system == 'Windows':
            args = [
                '-m',
                str(self.toCygwinPath(self.mDirPath)), '-D',
                str(self.toCygwinPath(self.dataPath)), '-l',
                str(self.logFilePath)
            ]
        else:
            args = ['-m', str(self.mDirPath), '-D', str(self.dataPath)]

        args += ['-p', str(self.listenPort)]

        if self.useTor and 0:
            args.append('-T')

        if await self.runProcess([NOTBIT] + args, self.nbProtocol):
            log.debug(f'Started notbit at PID: {self.process.pid}')

            await asyncWriteFile(str(self.pidFilePath),
                                 f"{self.process.pid}\n",
                                 mode='w+t')

            return True
        else:
            log.debug('Could not start nobit')

        return False
Пример #9
0
async def objectMetadata(cid, timeout=None, sslverify=True):
    """
    Returns object metadata for a CID from ipfs-search.com
    """

    timeout = cParentGet('search.ipfsSearch.getMetadataTimeout')
    try:
        with async_timeout.timeout(timeout):
            async with aiohttp.ClientSession() as session:
                async with session.get(
                    'https://{host}/v1/metadata/{cid}'.format(
                        host=ipfsSearchApiHost, cid=cid),
                        verify_ssl=sslverify) as resp:
                    payload = await resp.json()
                    return payload['metadata']
    except Exception:
        log.debug(f'Error occured while fetching metadata for CID: {cid}')
        return None
Пример #10
0
    async def watchMailDir(self):
        while True:
            await asyncio.sleep(cParentGet('mdirWatcher.sleepInterval'))

            log.debug(f'NotBit maildir ({self.clearMailDirPath}): reading')

            for key in self.clearMailDir.iterkeys():
                try:
                    message = self.clearMailDir[key]
                    recipient = message['To']
                    bmAddr, domain = recipient.split('@')
                    assert domain == 'bitmessage'
                    assert bmAddressValid(bmAddr)
                except email.errors.MessageParseError as err:
                    log.debug(f'Error parsing message {key}: {err}')
                    continue
                except Exception as err:
                    log.debug(f'Unknown error parsing message {key}: {err}')
                    continue
                else:
                    # Check if we have a mailbox for this recipient
                    mbox = self.mailBoxGet(bmAddr)

                    if not mbox:
                        log.debug(f'No mailbox for {recipient}')
                        await asyncio.sleep(0.05)
                        continue

                    log.debug(f'Found mailbox for {recipient}')
                    if await mbox.store(message):
                        # Delete the message from notbit's maildir
                        log.debug('Transferred message to destination maildir')

                        self.clearMailDir.remove(key)
                    else:
                        log.debug('Error transferring message to maildir')

                    await asyncio.sleep(0.1)
Пример #11
0
 def iconSize(self):
     size = cParentGet('unixfs.iconSize')
     return QSize(size, size)
Пример #12
0
    async def on_start(self):
        await super().on_start()

        if cParentGet('enabled') is True:
            await self.proc.start()
Пример #13
0
 def config(self):
     base = super().config()
     return configMerge(base, cParentGet('services.peers'))
Пример #14
0
 def config(self):
     return cParentGet('serviceTypes.base')
Пример #15
0
 def config(self):
     base = super().config()
     return configMerge(base, cParentGet('serviceTypes.curve25519EncJson'))
Пример #16
0
 def cUnixFs(self):
     return cParentGet('unixfs')
Пример #17
0
 def cNsCache(self):
     return cParentGet('nsCache')