Esempio n. 1
0
def connect(ip='',port=0,password=''):
    from cjdnsadmin import connect, connectWithAdminInfo
    try:
        cjdns = connect(ip,int(port), password)
    except:
        cjdns = connectWithAdminInfo()
    return cjdns
Esempio n. 2
0
def peers(pl):
    """Returns the current number of peers connected"""
    try:
        cjdns = cjdnsadmin.connectWithAdminInfo()
    except ImportError:
        return None
    peercount = 0
    localpeers = 0
    page = 0
    more = True
    while more:
        table = cjdns.InterfaceController_peerStats(page)
        more = "more" in table
        page += 1
        for peer in table['peers']:
            if peer['state'] != "UNRESPONSIVE":
                if "user" in peer:
                    if peer['user'] == "Local Peers":
                        localpeers += 1
                    else:
                        peercount += 1
                else:
                    peercount += 1
    out = [
        {
            "contents": str(peercount),
            "highlight_group": ["cjdns:peers"]
        }
    ]
    if localpeers > 0:
        out.append({
            "contents": str(localpeers),
            "highlight_group": ["cjdns:localpeers"]
            })
    return out
Esempio n. 3
0
 def versioncheck(self, irc, msg, args=None, nick=None):
     """[<nick>]
     
     Checks the cjdns version of <nick>, or your nick if no args are given."""
     host = None
     if nick is not None and args is not None:
         if nick in irc.state.nicksToHostmasks:
             hostmask = irc.state.nicksToHostmasks[nick]
             host = hostmask.split("@")[-1]
         else:
             irc.error("Can't find user %s" % nick)
     else:
         host = msg.host
     if host is not None:
         if nick is None:
             nick = msg.nick
         cjdns = cjdnsadmin.connectWithAdminInfo()
         ping = cjdns.RouterModule_pingNode(host)
         if "version" in ping:
             version = ping['version']
             if not version in self.versions:
                 github = requests.get("https://api.github.com/repos/cjdelisle/cjdns/commits/%s" % version).json()
                 self.versions[version] = datetime.strptime(github['commit']['author']['date'], "%Y-%m-%dT%H:%M:%SZ")
             if self.versions[version] > self.latest['time']:
                 github = requests.get("https://api.github.com/repos/cjdelisle/cjdns/commits").json()
                 self.latest = {
                     "time": datetime.strptime(github[0]['commit']['author']['date'], "%Y-%m-%dT%H:%M:%SZ"),
                     "sha": github[0]['sha']
                     }
                 for version in github:
                     self.versions[version['sha']] = datetime.strptime(version['commit']['author']['date'])
             committime = self.versions[version]
             hostmask = "%s!%s@%s" % (msg.nick, msg.user, msg.host)
             if version != self.latest['sha']:
                 if datetime.now() - committime > timedelta(weeks=4):
                     sendNotice = True
                     if hostmask not in self.recentnotices:
                         self.recentnotices[hostmask] = datetime.now()
                     else:
                         if datetime.now() - self.recentnotices[hostmask] < timedelta(hours=6):
                             sendNotice = False
                     if sendNotice:
                         self.log.info("%s is running a commit from %s" % (msg.nick, pretty.date(committime)))
                         irc.queueMsg(ircmsgs.privmsg("#hyperboria", "%s is running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update." % (msg.nick, pretty.date(committime))))
                 elif datetime.now() - committime > timedelta(weeks=2):
                     sendNotice = True
                     if hostmask not in self.recentnotices:
                         self.recentnotices[hostmask] = datetime.now()
                     else:
                         if datetime.now() - self.recentnotices[hostmask] < timedelta(hours=6):
                             sendNotice = False
                     if sendNotice:
                         self.log.info("%s is running a commit from %s" % (msg.nick, pretty.date(committime)))
                         irc.queueMsg(ircmsgs.notice(msg.nick, "You're running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update." % pretty.date(committime)))
             elif args is not None:
                 irc.reply("%s is up to date" % nick)
                 irc.reply("%s is running %s (from %s)" % (nick, version, pretty.date(committime)))
         elif "error" in ping and args is not None:
             irc.reply("Error checking version of %s: %s" % (host, ping['error']))
Esempio n. 4
0
 def fetchPeersFromProvider(self):
   cjdns = cjdnsadmin.connectWithAdminInfo()
   more = True
   page = 0
   while more:
     table = cjdns.NodeStore_dumpTable(page)
     for node in table['routingTable']:
       self.addPeer(node['ip'] + ":" + str(self.port))
     more = "more" in table
     page += 1
Esempio n. 5
0
    def update(self, oldnodes):
        try:
            cjdns = cjdnsadmin.connectWithAdminInfo()
        except ImportError:
            return None

        more = True
        page = 0
        routes = 0
        nodes = []
        while more:
            table = cjdns.NodeStore_dumpTable(page)
            more = "more" in table
            routes += len(table['routingTable'])
            for route in table['routingTable']:
                if not route['ip'] in nodes:
                    nodes.append(route['ip'])
            page += 1
        return nodes
Esempio n. 6
0
def connect(ip='127.0.0.1', port=11234, password=''):
    from cjdnsadmin import connectWithAdminInfo
    return connectWithAdminInfo()
Esempio n. 7
0
        params = {"token": token, "title": title, "message": message}
        url = "https://www.thefinn93.com/push/send?" + urlencode(params)
        urllib2.urlopen(url)
    print message

try:
    import cjdnsadmin
except ImportError:
    sys.path.append("/opt/cjdns/contrib/python/cjdnsadmin")
    try:
        import cjdnsadmin
    except ImportError:
        notify("Failed to import cjdnsadmin!")
        sys.exit(1)

cjdns = cjdnsadmin.connectWithAdminInfo()

if not os.path.isfile("/tmp/stoppeercron"):
    try:
        data = json.load(open(sys.argv[1]))
    except IOError:
        data = {}
    except ValueError:
        print "Teh JSONz are fux0r'd"
        open("/tmp/stoppeercron", "a").close()
        sys.exit(1)
else:
    sys.exit(0)


if "version" not in data:
Esempio n. 8
0
#!/usr/bin/env python2
# You may redistribute this program and/or modify it under the terms of
# the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import sys
import os
import cjdnsadmin

s = cjdnsadmin.connectWithAdminInfo()

print("Interactive cjdns admin shell.")
print("Usage: `s.command()`. 's' for Session.")
print("Try s.ping() or s.functions() to start.")
print("Ctrl-D to exit.")
Esempio n. 9
0
def connect(ip='127.0.0.1', port=11234, password=''):
    from cjdnsadmin import connectWithAdminInfo
    return connectWithAdminInfo()
Esempio n. 10
0
import os
import sys
import json
import re
from hashlib import sha512

try:
    from cjdnsadmin import connect,connectWithAdminInfo
except ImportError:
    sys.path.insert(0, os.getenv("cjdnsadmin","/opt/cjdns/contrib/python/cjdnsadmin"))
    from cjdnsadmin import connect,connectWithAdminInfo

if os.getenv("cjdns_password") is not None:
    cjdns = connect(os.getenv("cjdns_ip", "127.0.0.1"), int(os.getenv("cjdns_port", "11234")), os.getenv("cjdns_password"))
else:
    cjdns = connectWithAdminInfo()

try:
    cjdns.InterfaceController_peerStats()
except AttributeError:
    print "InterfaceController_peerStats() not a function"
    print "Do you have an old version of cjdns?"
    print "possibly the stable-0.4 branch."
    sys.exit(1)

## Stolen from contrib/python/cjdnsadmin/publicToIp6.py ##

# see util/Base32.h
def Base32_decode(input):
    output = bytearray(len(input));
    numForAscii = [
Esempio n. 11
0
#!/usr/bin/env python
import sys, os
try:
    from cjdnsadmin import connect, connectWithAdminInfo
except ImportError:
    sys.path.append(
        os.getenv("cjdnsadmin", "/opt/cjdns/contrib/python/cjdnsadmin"))
    from cjdnsadmin import connect, connectWithAdminInfo

if os.getenv("cjdns_password") is not None:
    cjdns = connect(os.getenv("cjdns_ip", "127.0.0.1"),
                    int(os.getenv("cjdns_port", "11234")),
                    os.getenv("cjdns_password"))
else:
    cjdns = connectWithAdminInfo()

config = False
if len(sys.argv) > 1:
    if sys.argv[1] == "config":
        config = True

allPeers = {}

i = 0
while True:
    ps = cjdns.InterfaceController_peerStats(i)
    peers = ps['peers']
    for p in peers:
        name = p['publicKey'][-10:]
        if "user" in p:
            name = p['user']
Esempio n. 12
0
def parse(args):
    """ parse the command line arguments """

    try:
        return getopt.getopt(args, 'phc:', ['pretty', 'help', 'config='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)


if __name__ == "__main__":

    options, remainder = parse(sys.argv[1:])
    transform = lambda s: s
    connect = lambda: cjdnsadmin.connectWithAdminInfo()

    for opt, arg in options:
        if opt in ('-c', '--config'):
            connect = lambda: cjdnsadmin.connectWithAdminInfo(arg)
        elif opt in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif opt in ('-p', '--pretty'):
            transform = lambda s: json.dumps(
                s, sort_keys=True, indent=4, separators=(',', ': '))

    if remainder:
        s = connect()
        result = eval('s.' + string.join(remainder, " "))
        if result:
Esempio n. 13
0
def parse(args):
    """ parse the command line arguments """

    try:
        return getopt.getopt(args, "phc:", ["pretty", "help", "config="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)


if __name__ == "__main__":

    options, remainder = parse(sys.argv[1:])
    transform = lambda s: s
    connect = lambda: cjdnsadmin.connectWithAdminInfo()

    for opt, arg in options:
        if opt in ("-c", "--config"):
            connect = lambda: cjdnsadmin.connectWithAdminInfo(arg)
        elif opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-p", "--pretty"):
            transform = lambda s: json.dumps(s, sort_keys=True, indent=4, separators=(",", ": "))

    if remainder:
        s = connect()
        result = eval("s." + string.join(remainder, " "))
        if result:
            print transform(result)
Esempio n. 14
0
def cjdns_connect(process=0):
	if cjdns_use_default:
		return cjdnsadmin.connectWithAdminInfo()
	else:
		return cjdnsadmin.connect(cjdns_ip, cjdns_first_port + process, cjdns_password)
Esempio n. 15
0
def cjdns_connect(process=0):
	if cjdns_use_default:
		return cjdnsadmin.connectWithAdminInfo()
	else:
		return cjdnsadmin.connect(cjdns_ip, cjdns_first_port + process, cjdns_password)
Esempio n. 16
0
 def versioncheck(self, irc, msg, args=None, nick=None):
     """[<nick>]
     
     Checks the cjdns version of <nick>, or your nick if no args are given."""
     host = None
     if nick is not None and args is not None:
         if nick in irc.state.nicksToHostmasks:
             hostmask = irc.state.nicksToHostmasks[nick]
             host = hostmask.split("@")[-1]
         else:
             irc.error("Can't find user %s" % nick)
     else:
         host = msg.host
     if host is not None:
         if nick is None:
             nick = msg.nick
         hostmask = "%s!%s@%s" % (msg.nick, msg.user, msg.host)
         sendNotice = True
         if hostmask not in self.recentnotices:
             self.recentnotices[hostmask] = datetime.now()
         else:
             if datetime.now() - self.recentnotices[hostmask] < timedelta(
                     hours=6):
                 sendNotice = False
         if sendNotice or args is not None:
             cjdns = cjdnsadmin.connectWithAdminInfo()
             ping = cjdns.RouterModule_pingNode(
                 host, self.registryValue('timeout'))
             if "version" in ping:
                 version = ping['version']
                 if not version in self.versions:
                     github = requests.get(
                         "https://api.github.com/repos/cjdelisle/cjdns/commits/%s"
                         % version).json()
                     self.versions[version] = datetime.strptime(
                         github['commit']['author']['date'],
                         "%Y-%m-%dT%H:%M:%SZ")
                 if self.versions[version] > self.latest['time']:
                     github = requests.get(
                         "https://api.github.com/repos/cjdelisle/cjdns/commits"
                     ).json()
                     self.latest = {
                         "time":
                         datetime.strptime(
                             github[0]['commit']['author']['date'],
                             "%Y-%m-%dT%H:%M:%SZ"),
                         "sha":
                         github[0]['sha']
                     }
                     for version in github:
                         self.versions[version['sha']] = datetime.strptime(
                             version['commit']['author']['date'])
                 committime = self.versions[version]
                 if version != self.latest['sha']:
                     if datetime.now() - committime > timedelta(weeks=4):
                         self.log.info("%s is running a commit from %s" %
                                       (msg.nick, pretty.date(committime)))
                         irc.queueMsg(
                             ircmsgs.privmsg(
                                 msg.args[0],
                                 "%s is running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update."
                                 % (msg.nick, pretty.date(committime))))
                     elif datetime.now() - committime > timedelta(weeks=2):
                         self.log.info("%s is running a commit from %s" %
                                       (msg.nick, pretty.date(committime)))
                         irc.queueMsg(
                             ircmsgs.notice(
                                 msg.nick,
                                 "You're running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update."
                                 % pretty.date(committime)))
                 elif args is not None:
                     irc.reply("%s is up to date" % nick)
                     irc.reply("%s is running %s (from %s)" %
                               (nick, version, pretty.date(committime)))
             elif "error" in ping and args is not None:
                 irc.reply("Error checking version of %s: %s" %
                           (host, ping['error']))