From 97016383052fcdb880e85b4db746eef83b4f2e81 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Mon, 6 Jun 2011 20:21:40 -0400 Subject: [PATCH 001/692] bugfix in branch names with .git checkout --- irc/commands/git.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/irc/commands/git.py b/irc/commands/git.py index 7b76cf8..9ca793d 100644 --- a/irc/commands/git.py +++ b/irc/commands/git.py @@ -101,12 +101,13 @@ class Git(BaseCommand): self.connection.reply(self.data, "switch to which branch?") return + current_branch = self.exec_shell("git name-rev --name-only HEAD") + try: result = self.exec_shell("git checkout %s" % branch) if "Already on" in result: self.connection.reply(self.data, "already on \x0302%s\x0301!" % branch) else: - current_branch = self.exec_shell("git name-rev --name-only HEAD") self.connection.reply(self.data, "switched from branch \x0302%s\x0301 to \x0302%s\x0301." % (current_branch, branch)) except subprocess.CalledProcessError: # git couldn't switch branches From 665ee391fb0b66f397defd65807f0801ce30081c Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Mon, 6 Jun 2011 21:09:14 -0400 Subject: [PATCH 002/692] deleted old config files and started from scratch with config/main.cfg and config/secure.cfg; the parser will be in core/config.py --- .gitignore | 2 +- config/irc.py | 25 --------------- config/{__init__.py => main.cfg} | 0 config/main.py | 24 -------------- config/schedule.py | 28 ---------------- config/secure.default.py | 9 ------ config/watcher.py | 69 ---------------------------------------- core/config.py | 0 8 files changed, 1 insertion(+), 156 deletions(-) delete mode 100644 config/irc.py rename config/{__init__.py => main.cfg} (100%) delete mode 100644 config/main.py delete mode 100644 config/schedule.py delete mode 100644 config/secure.default.py delete mode 100644 config/watcher.py create mode 100644 core/config.py diff --git a/.gitignore b/.gitignore index 282791f..58121c0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ *.pyc # Ignore secure config files: -config/secure.py +config/secure.cfg # Ignore pydev's nonsense: .project diff --git a/config/irc.py b/config/irc.py deleted file mode 100644 index ee9ef3e..0000000 --- a/config/irc.py +++ /dev/null @@ -1,25 +0,0 @@ -# -*- coding: utf-8 -*- - -# EarwigBot Configuration File -# This file contains information that the bot uses to connect to IRC. - -# our main (front-end) server's hostname and port -HOST = "irc.freenode.net" -PORT = 6667 - -# our watcher server's hostname, port, and RC channel -WATCHER_HOST = "irc.wikimedia.org" -WATCHER_PORT = 6667 -WATCHER_CHAN = "#en.wikipedia" - -# our nick, ident, and real name, used on both servers -NICK = "EarwigBot" -IDENT = "earwigbot" -REALNAME = "[[w:en:User:EarwigBot]]" - -# channels to join on main server's startup -CHANS = ["##earwigbot", "##earwig", "#wikipedia-en-afc"] - -# hardcoded hostnames of users with certain permissions -OWNERS = ["wikipedia/The-Earwig"] # can use owner-only commands (!restart and !git) -ADMINS = ["wikipedia/The-Earwig", "wikipedia/LeonardBloom"] # can use high-risk commands, e.g. !op diff --git a/config/__init__.py b/config/main.cfg similarity index 100% rename from config/__init__.py rename to config/main.cfg diff --git a/config/main.py b/config/main.py deleted file mode 100644 index 6e8c082..0000000 --- a/config/main.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# EarwigBot Configuration File -# This file tells the bot which of its components should be enabled. - -# The IRC frontend (configured in config/irc.py) sits on a public IRC network, -# responds to commands given to it, and reports edits (if the IRC watcher -# component is enabled). -enable_irc_frontend = True - -# The IRC watcher (connection details configured in config/irc.py as well) sits -# on an IRC network that gives a recent changes feed, usually irc.wikimedia.net. -# It looks for edits matching certain (often regex) patterns (rules configured -# in config/watcher.py), and either reports them to the IRC frontend (if -# enabled), or activates a task on the WikiBot (if configured to do). -enable_irc_watcher = True - -# EarwigBot doesn't have to edit a wiki, although this is its main purpose. If -# the wiki schedule is disabled, it will not be able to handle scheduled tasks -# that involve editing (such as creating a daily category every day at midnight -# UTC), but it can still edit through rules given in the watcher, and bot tasks -# can still be activated by the command line. The schedule is configured in -# config/schedule.py. -enable_wiki_schedule = True diff --git a/config/schedule.py b/config/schedule.py deleted file mode 100644 index 093050b..0000000 --- a/config/schedule.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- - -# EarwigBot Configuration File -# This file tells the bot when to run certain wiki-editing tasks. - -def check(minute, hour, month_day, month, week_day): - tasks = [] # tasks to run this turn, each as a tuple of (task_name, kwargs) or just task_name - - if minute == 0: # run every hour on the hour - tasks.append(("afc_statistics", {"action": "save"})) # save statistics to [[Template:AFC_statistics]] - - if hour == 0: # run every day at midnight - tasks.append("afc_dailycats") # create daily categories for WP:AFC - tasks.append("feed_dailycats") # create daily categories for WP:FEED - - if week_day == 0: # run every Sunday at midnight (that is, the start of Sunday, not the end) - tasks.append("afc_undated") # clear [[Category:Undated AfC submissions]] - - if week_day == 1: # run every Monday at midnight - tasks.append("afc_catdelink") # delink mainspace categories in declined AfC submissions - - if week_day == 2: # run every Tuesday at midnight - tasks.append("wrongmime") # tag files whose extensions do not agree with their MIME type - - if week_day == 3: # run every Wednesday at midnight - tasks.append("blptag") # add |blp=yes to {{WPB}} or {{WPBS}} when it is used along with {{WP Biography}} - - return tasks diff --git a/config/secure.default.py b/config/secure.default.py deleted file mode 100644 index 0db882e..0000000 --- a/config/secure.default.py +++ /dev/null @@ -1,9 +0,0 @@ -# -*- coding: utf-8 -*- - -# EarwigBot Configuration File -# This file contains information that should be kept hidden, including passwords. - -# IRC: identify ourselves to NickServ? -NS_AUTH = False -NS_USER = "" -NS_PASS = "" diff --git a/config/watcher.py b/config/watcher.py deleted file mode 100644 index 6e2fe28..0000000 --- a/config/watcher.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- - -# EarwigBot Configuration File -# This file contains rules for the bot's watcher component. - -import re - -from wiki import task_manager - -# Define different report channels on our front-end server. They /must/ be in CHANS in config/irc.py or the bot will not be able to send messages to them (unless they have -n set). -AFC_CHANS = ["#wikipedia-en-afc"] # report recent AfC changes/give AfC status messages upon join -BOT_CHANS = ["##earwigbot", "#wikipedia-en-afc"] # report edits containing "!earwigbot" - -# Define some commonly used strings. -afc_prefix = "wikipedia( talk)?:(wikiproject )?articles for creation" - -# Define our compiled regexps used when finding certain edits. -r_page = re.compile(afc_prefix) -r_ffu = re.compile("wikipedia( talk)?:files for upload") -r_move1 = re.compile("moved \[\[{}".format(afc_prefix)) # an AFC page was either moved locally or out -r_move2 = re.compile("moved \[\[(.*?)\]\] to \[\[{}".format(afc_prefix)) # an outside page was moved into AFC -r_moved_pages = re.compile("^moved \[\[(.*?)\]\] to \[\[(.*?)\]\]") -r_delete = re.compile("deleted \"\[\[{}".format(afc_prefix)) -r_deleted_page = re.compile("^deleted \"\[\[(.*?)\]\]") -r_restore = re.compile("restored \"\[\[{}".format(afc_prefix)) -r_restored_page = re.compile("^restored \"\[\[(.*?)\]\]") -r_protect = re.compile("protected \"\[\[{}".format(afc_prefix)) - -def process(rc): - chans = set() # channels to report this message to - page_name = rc.page.lower() - comment = rc.comment.lower() - - if "!earwigbot" in rc.msg.lower(): - chans.update(BOT_CHANS) - - if r_page.search(page_name): - task_manager.start_task("afc_statistics", action="process_edit", page=rc.page) - task_manager.start_task("afc_copyvios", action="process_edit", page=rc.page) - chans.update(AFC_CHANS) - - elif r_ffu.match(page_name): - chans.update(AFC_CHANS) - - elif page_name.startswith("template:afc submission"): - chans.update(AFC_CHANS) - - elif rc.flags == "move" and (r_move1.match(comment) or r_move2.match(comment)): - p = r_moved_pages.findall(rc.comment)[0] - task_manager.start_task("afc_statistics", action="process_move", pages=p) - task_manager.start_task("afc_copyvios", action="process_move", pages=p) - chans.update(AFC_CHANS) - - elif rc.flags == "delete" and r_delete.match(comment): - p = r_deleted_page.findall(rc.comment)[0][0] - task_manager.start_task("afc_statistics", action="process_delete", page=p) - task_manager.start_task("afc_copyvios", action="process_delete", page=p) - chans.update(AFC_CHANS) - - elif rc.flags == "restore" and r_restore.match(comment): - p = r_restored_page.findall(rc.comment)[0][0] - task_manager.start_task("afc_statistics", action="process_restore", page=p) - task_manager.start_task("afc_copyvios", action="process_restore", page=p) - chans.update(AFC_CHANS) - - elif rc.flags == "protect" and r_protect.match(comment): - chans.update(AFC_CHANS) - - return chans diff --git a/core/config.py b/core/config.py new file mode 100644 index 0000000..e69de29 From e96189593d31aeaec7d7dd270c8fbca6422d0992 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 7 Jun 2011 11:34:24 -0400 Subject: [PATCH 003/692] removed config check from earwigbot.py launcher --- earwigbot.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/earwigbot.py b/earwigbot.py index f7852ef..ff93bcc 100644 --- a/earwigbot.py +++ b/earwigbot.py @@ -3,13 +3,6 @@ import time from subprocess import * -try: - from config import irc, main, schedule, secure, watcher -except ImportError: - print """Missing a config file! Make sure you have configured the bot. All *.py.default files in config/ -should have their .default extension removed, and the info inside should be corrected.""" - exit() - def main(): while 1: call(['python', 'core/main.py']) From d3abfc3370e30925d3f7110cb8d5e2ff7ca81bcb Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 7 Jun 2011 20:52:16 -0400 Subject: [PATCH 004/692] convert README to markdown (hopefully) --- README | 20 -------------------- README.md | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 20 deletions(-) delete mode 100644 README create mode 100644 README.md diff --git a/README b/README deleted file mode 100644 index 54e2260..0000000 --- a/README +++ /dev/null @@ -1,20 +0,0 @@ -EarwigBot[1] is a Python[2] robot that edits Wikipedia. - -Development began, based on the Pywikipedia framework[3], in early 2009. -Approval for its fist task, a copyright violation detector[4], was carried out -in May, and the bot has been running consistently ever since (with the -exception of Jan/Feb 2011). It currently handles several ongoing tasks[5], -ranging from statistics generation to category cleanup, and on-demand tasks -such as WikiProject template tagging. Since it started running, the bot has -made over 45,000 edits. - -A project to rewrite it from scratch began in early April 2011, thus moving -away from the Pywikipedia framework and allowing for less overall code, better -integration between bot parts, and easier maintenance. - -Links: -[1] http://toolserver.org/~earwig/earwigbot/ -[2] http://python.org/ -[3] http://pywikipediabot.sourceforge.net/ -[4] http://en.wikipedia.org/wiki/Wikipedia:Bots/Requests_for_approval/EarwigBot_1 -[5] http://en.wikipedia.org/wiki/User:EarwigBot#Tasks diff --git a/README.md b/README.md new file mode 100644 index 0000000..9fc4c81 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +[EarwigBot](http://toolserver.org/~earwig/earwigbot/) is a +[Python](http://python.org/) robot that edits Wikipedia. + +# History + +Development began, based on the +[Pywikipedia framework](http://pywikipediabot.sourceforge.net/), in early 2009. +Approval for its fist task, a +[copyright violation detector](http://en.wikipedia.org/wiki/Wikipedia:Bots/Requests_for_approval/EarwigBot_1), +was carried out in May, and the bot has been running consistently ever since +(with the exception of Jan/Feb 2011). It currently handles +[several ongoing tasks](http://en.wikipedia.org/wiki/User:EarwigBot#Tasks), +ranging from statistics generation to category cleanup, and on-demand tasks +such as WikiProject template tagging. Since it started running, the bot has +made over 45,000 edits. + +A project to rewrite it from scratch began in early April 2011, thus moving +away from the Pywikipedia framework and allowing for less overall code, better +integration between bot parts, and easier maintenance. From e105a8dd785ec15fe06989dca667ee748973f444 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 7 Jun 2011 21:37:56 -0400 Subject: [PATCH 005/692] some stuff; nothing really substantial and probably doesn't work, but I wanted to get this out on paper --- core/config.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ core/main.py | 11 +++++++---- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/core/config.py b/core/config.py index e69de29..f72a4a4 100644 --- a/core/config.py +++ b/core/config.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +## EarwigBot's Config File Parser + +from collections import defaultdict +import ConfigParser as configparser +import os + +main_cfg_path = os.path.join("config", "main.cfg") +secure_cfg_path = os.path.join("config", "secure.cfg") + +config = dict() + +def load_config_file(filename): + parser = configparser.SafeConfigParser() + parser.optionxform = str # don't lowercase option names automatically + parser.read(filename) + return parser + +def make_new_config(): + print "You haven't configured the bot yet!" + choice = raw_input("Would you like to do this now? [y/n] ") + if choice.lower().startswith("y"): + pass + else: + exit() + +def dump_config_to_dict(parsers): + global config + for parser in parsers: + for section in parser.sections(): + for option in parser.options(section): + try: + config[section][option] = parser.get(section, option) + except KeyError: + config[section] = defaultdict(lambda: None) + config[section][option] = parser.get(section, option) + +def load(): + if not os.path.exists(main_cfg_path): + make_new_config() + + main_cfg = load_config_file(main_cfg_path) + secure_cfg = load_config_file(secure_cfg_path) + + dump_config_to_dict([main_cfg, secure_cfg]) diff --git a/core/main.py b/core/main.py index 3000def..a5d7f2f 100644 --- a/core/main.py +++ b/core/main.py @@ -28,7 +28,7 @@ import os parent_dir = os.path.split(sys.path[0])[0] sys.path.append(parent_dir) # make sure we look in the parent directory for modules -from config.main import * +from core import config from irc import frontend, watcher from wiki import task_manager @@ -96,10 +96,13 @@ def irc_frontend(): f_conn.close() def run(): - if enable_irc_frontend: # make the frontend run on our primary thread if enabled, and enable additional components through that function + config.load() + components = config.config["main"] + + if components["enable_irc_frontend"]: # make the frontend run on our primary thread if enabled, and enable additional components through that function irc_frontend() - elif enable_wiki_schedule: # the scheduler is enabled - run it on the main thread, but also run the IRC watcher on another thread if it is enabled + elif components["enable_wiki_schedule"]: # the scheduler is enabled - run it on the main thread, but also run the IRC watcher on another thread if it is enabled print "\nStarting wiki scheduler..." task_manager.load_tasks() if enable_irc_watcher: @@ -109,7 +112,7 @@ def run(): t_watcher.start() wiki_scheduler() - elif enable_irc_watcher: # the IRC watcher is our only enabled component, so run its function only and don't worry about anything else + elif components["enable_irc_watcher"]: # the IRC watcher is our only enabled component, so run its function only and don't worry about anything else irc_watcher() else: # nothing is enabled! From 13cfffb5c07697009313b62f9ae70aa005aec53f Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 14 Jun 2011 20:44:07 -0400 Subject: [PATCH 006/692] making entire config/ folder ignored by git; there's no reason to track this bot-specific information --- .gitignore | 4 ++-- config/main.cfg | 0 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 config/main.cfg diff --git a/.gitignore b/.gitignore index 58121c0..3a07a6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ # Ignore python bytecode: *.pyc -# Ignore secure config files: -config/secure.cfg +# Ignore bot-specific config files: +config/ # Ignore pydev's nonsense: .project diff --git a/config/main.cfg b/config/main.cfg deleted file mode 100644 index e69de29..0000000 From c8add512f4eaf20acfcf5ec818fc9b5cc8a2076b Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 16 Jun 2011 17:41:43 -0400 Subject: [PATCH 007/692] dropping config/ subdirectory in favor of a single config.xml file, located in the bot's root dir, with encrypted passwords instead of a secure.xml file --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 3a07a6a..868c046 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ # Ignore python bytecode: *.pyc -# Ignore bot-specific config files: -config/ +# Ignore bot-specific config file: +config.xml # Ignore pydev's nonsense: .project From a568ec67773b9299be30912a8db850c2ddca6f5b Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 16 Jun 2011 17:45:16 -0400 Subject: [PATCH 008/692] lots of work on config.py, earwigbot.py, and main.py; TODO: actually parse config files; convert components to new config format; make_new_config() --- core/config.py | 122 +++++++++++++++++++++++++++++++++++++++----------------- core/main.py | 124 +++++++++++++++++++++++++++++++++------------------------ earwigbot.py | 49 ++++++++++++++++++++--- 3 files changed, 202 insertions(+), 93 deletions(-) diff --git a/core/config.py b/core/config.py index f72a4a4..f7c5785 100644 --- a/core/config.py +++ b/core/config.py @@ -1,46 +1,94 @@ # -*- coding: utf-8 -*- -## EarwigBot's Config File Parser +""" +EarwigBot's XML Config File Parser -from collections import defaultdict -import ConfigParser as configparser -import os +This handles all tasks involving reading and writing to our config file, +including encrypting and decrypting passwords and making a new config file from +scratch at the inital bot run. +""" -main_cfg_path = os.path.join("config", "main.cfg") -secure_cfg_path = os.path.join("config", "secure.cfg") +from os import makedirs, path +from xml.dom import minidom +from xml.parsers.expat import ExpatError -config = dict() +script_dir = path.dirname(path.abspath(__file__)) +root_dir = path.split(script_dir)[0] +config_path = path.join(root_dir, "config.xml") -def load_config_file(filename): - parser = configparser.SafeConfigParser() - parser.optionxform = str # don't lowercase option names automatically - parser.read(filename) - return parser +_config = None -def make_new_config(): - print "You haven't configured the bot yet!" - choice = raw_input("Would you like to do this now? [y/n] ") - if choice.lower().startswith("y"): - pass +class ConfigParseException(Exception): + """Base exception for when we could not parse the config file.""" + +class TypeMismatchException(ConfigParseException): + """A field does not fit to its expected type; e.g., an aribrary string + where we expected a boolean or integer.""" + +def _load_config(): + """Load data from our XML config file (config.xml) into a DOM object.""" + global _config + _config = minidom.parse(config_path) + +def verify_config(): + """Check to see if we have a valid config file, and if not, notify the + user. If there is no config file at all, offer to make one; otherwise, + exit.""" + if path.exists(config_path): + try: + _load_config() + except ExpatError as error: + print "Could not parse config file {0}:\n{1}".format(config_path, + error) + exit() + else: + return are_passwords_encrypted() else: - exit() - -def dump_config_to_dict(parsers): - global config - for parser in parsers: - for section in parser.sections(): - for option in parser.options(section): - try: - config[section][option] = parser.get(section, option) - except KeyError: - config[section] = defaultdict(lambda: None) - config[section][option] = parser.get(section, option) - -def load(): - if not os.path.exists(main_cfg_path): - make_new_config() - - main_cfg = load_config_file(main_cfg_path) - secure_cfg = load_config_file(secure_cfg_path) + print "You haven't configured the bot yet!" + choice = raw_input("Would you like to do this now? [y/n] ") + if choice.lower().startswith("y"): + return make_new_config() + else: + exit() + +def make_new_config(): + """Make a new XML config file based on the user's input.""" + makedirs(config_dir) - dump_config_to_dict([main_cfg, secure_cfg]) + encrypt = raw_input("Would you like to encrypt passwords stored in " + + "config.xml? [y/n] ") + if encrypt.lower().startswith("y"): + is_encrypted = True + else: + is_encrypted = False + + return is_encrypted + +def are_passwords_encrypted(): + """Determine if the passwords in our config file are encrypted, returning + either True or False.""" + data = _config.getElementsByTagName("config")[0] + element = data.getElementsByTagName("encrypt-passwords")[0] + return attribute_to_bool(element, "enabled") + +def attribute_to_bool(element, attribute): + """Return True if the value of element's attribute is 'true', '1', or 'on'; + return False if it is 'false', '0', or 'off' (regardless of + capitalization); raise TypeMismatchException if it does match any of + those.""" + value = element.getAttribute(attribute).lower() + if value in ["true", "1", "on"]: + return True + elif value in ["false", "0", "off"]: + return False + else: + e = ("Expected a bool in attribute '{0}' of element '{1}', but " + + "got '{2}'.").format(attribute, element.tagName, value) + raise TypeMismatchException(e) + +def parse_config(key): + """Parse config data from a DOM object. The key is used to unencrypt + passwords stored in the config file.""" + _load_config() # we might be re-loading unnecessarily here, but no harm in + # that! + data = _config.getElementsByTagName("config")[0] diff --git a/core/main.py b/core/main.py index a5d7f2f..b4e9729 100644 --- a/core/main.py +++ b/core/main.py @@ -1,23 +1,34 @@ +#! /usr/bin/python # -*- coding: utf-8 -*- -## EarwigBot's Core - -## EarwigBot has three components that can run independently of each other: an -## IRC front-end, an IRC watcher, and a wiki scheduler. -## * The IRC front-end runs on a normal IRC server and expects users to -## interact with it/give it commands. -## * The IRC watcher runs on a wiki recent-changes server and listens for -## edits. Users cannot interact with this part of the bot. -## * The wiki scheduler runs wiki-editing bot tasks in separate threads at -## user-defined times through a cron-like interface. - -## There is a "priority" system here: -## 1. If the IRC frontend is enabled, it will run on the main thread, and the -## IRC watcher and wiki scheduler (if enabled) will run on separate threads. -## 2. If the wiki scheduler is enabled, it will run on the main thread, and the -## IRC watcher (if enabled) will run on a separate thread. -## 3. If the IRC watcher is enabled, it will run on the main (and only) thread. -## Else, the bot will stop, as no components are enabled. +""" +EarwigBot's Core + +This (should) not be run directly; the wrapper in "earwigbot.py" is preferred, +but it should work fine alone, as long as you enter the password-unlock key at +the initial hidden prompt. + +The core is essentially responsible for starting the various bot components +(irc, scheduler, etc) and making sure they are all happy. An explanation of the +different components follows: + +EarwigBot has three components that can run independently of each other: an IRC +front-end, an IRC watcher, and a wiki scheduler. +* The IRC front-end runs on a normal IRC server and expects users to interact + with it/give it commands. +* The IRC watcher runs on a wiki recent-changes server and listens for edits. + Users cannot interact with this part of the bot. +* The wiki scheduler runs wiki-editing bot tasks in separate threads at + user-defined times through a cron-like interface. + +There is a "priority" system here: +1. If the IRC frontend is enabled, it will run on the main thread, and the IRC + watcher and wiki scheduler (if enabled) will run on separate threads. +2. If the wiki scheduler is enabled, it will run on the main thread, and the + IRC watcher (if enabled) will run on a separate thread. +3. If the IRC watcher is enabled, it will run on the main (and only) thread. +Else, the bot will stop, as no components are enabled. +""" import threading import time @@ -25,12 +36,14 @@ import traceback import sys import os -parent_dir = os.path.split(sys.path[0])[0] -sys.path.append(parent_dir) # make sure we look in the parent directory for modules +script_dir = os.path.dirname(os.path.abspath(__file__)) +root_dir = os.path.split(script_dir)[0] # the bot's "root" directory relative + # to its different components +sys.path.append(root_dir) # make sure we look in the root dir for modules from core import config -from irc import frontend, watcher -from wiki import task_manager +#from irc import frontend, watcher +#from wiki import task_manager f_conn = None w_conn = None @@ -39,16 +52,15 @@ def irc_watcher(f_conn): """Function to handle the IRC watcher as another thread (if frontend and/or scheduler is enabled), otherwise run as the main thread.""" global w_conn - print "\nStarting IRC watcher..." - while 1: # restart the watcher component if (just) it breaks + while 1: # restart the watcher component if it breaks (and nothing else) w_conn = watcher.get_connection() w_conn.connect() - print # print a blank line here to signify that the bot has finished starting up + print # blank line to signify that the bot has finished starting up try: watcher.main(w_conn, f_conn) except: traceback.print_exc() - time.sleep(5) # sleep a bit before restarting watcher + time.sleep(5) # sleep a bit before restarting watcher print "\nWatcher has stopped; restarting component..." def wiki_scheduler(): @@ -57,24 +69,24 @@ def wiki_scheduler(): while 1: time_start = time.time() now = time.gmtime(time_start) - + task_manager.start_tasks(now) - + time_end = time.time() time_diff = time_start - time_end - if time_diff < 60: # sleep until the next minute + if time_diff < 60: # sleep until the next minute time.sleep(60 - time_diff) -def irc_frontend(): +def irc_frontend(components): """If the IRC frontend is enabled, make it run on our primary thread, and enable the wiki scheduler and IRC watcher on new threads if they are enabled.""" global f_conn - - print "\nStarting IRC frontend..." + + print "Starting IRC frontend..." f_conn = frontend.get_connection() frontend.startup(f_conn) - + if enable_wiki_schedule: print "\nStarting wiki scheduler..." task_manager.load_tasks() @@ -82,8 +94,9 @@ def irc_frontend(): t_scheduler.name = "wiki-scheduler" t_scheduler.daemon = True t_scheduler.start() - + if enable_irc_watcher: + print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) t_watcher.name = "irc-watcher" t_watcher.daemon = True @@ -94,32 +107,41 @@ def irc_frontend(): if enable_irc_watcher: w_conn.close() f_conn.close() - + def run(): - config.load() - components = config.config["main"] - - if components["enable_irc_frontend"]: # make the frontend run on our primary thread if enabled, and enable additional components through that function - irc_frontend() - - elif components["enable_wiki_schedule"]: # the scheduler is enabled - run it on the main thread, but also run the IRC watcher on another thread if it is enabled - print "\nStarting wiki scheduler..." - task_manager.load_tasks() - if enable_irc_watcher: + try: + key = raw_input() # wait for our password unlock key from the bot's + except EOFError: # wrapper + key = None + config.parse_config(key) # load data from the config file and parse it + # using the unlock key + components = None + + if components["irc_frontend"]: # make the frontend run on our primary + irc_frontend(components) # thread if enabled, and enable additional + # components through that function + + elif components["wiki_schedule"]: # run the scheduler on the main + print "Starting wiki scheduler..." # thread, but also run the IRC + task_manager.load_tasks() # watcher on another thread iff it + if enable_irc_watcher: # is enabled + print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) t_watcher.name = "irc-watcher" t_watcher.daemon = True t_watcher.start() wiki_scheduler() - - elif components["enable_irc_watcher"]: # the IRC watcher is our only enabled component, so run its function only and don't worry about anything else - irc_watcher() - + + elif components["irc_watcher"]: # the IRC watcher is our only enabled + print "Starting IRC watcher..." # component, so run its function only + irc_watcher() # and don't worry about anything else + else: # nothing is enabled! - exit("\nNo bot parts are enabled; stopping...") + print "No bot parts are enabled; stopping..." if __name__ == "__main__": try: run() except KeyboardInterrupt: - exit("\nKeyboardInterrupt: stopping main bot loop.") + print "\nKeyboardInterrupt: stopping main bot loop." + exit(1) diff --git a/earwigbot.py b/earwigbot.py index ff93bcc..b18f1bc 100644 --- a/earwigbot.py +++ b/earwigbot.py @@ -1,15 +1,54 @@ +#! /usr/bin/python # -*- coding: utf-8 -*- -import time -from subprocess import * +""" +EarwigBot + +A thin wrapper for EarwigBot's main bot code, located in core/main.py. This +wrapper will automatically restart the bot when it shuts down (from !restart, +for example). It requests the bot's password at startup and reuses it every +time the bot restarts internally, so you do not need to re-enter the password +after using !restart. + +For information about the bot as a whole, see the attached README.md file (in +markdown format!) and the LICENSE for licensing information. +""" + +from getpass import getpass +from subprocess import Popen, PIPE +from sys import executable +from time import sleep + +from core.config import verify_config + +__author__ = "Ben Kurtovic" +__copyright__ = "Copyright (c) 2009-2011 by Ben Kurtovic" +__license__ = "MIT License" +__version__ = "0.1dev" +__email__ = "ben.kurtovic@verizon.net" def main(): + print "EarwigBot v{0}\n".format(__version__) + + is_encrypted = verify_config() + if is_encrypted: # passwords in the config file are encrypted + key = getpass("Enter key to unencrypt bot passwords: ") + else: + key = None + while 1: - call(['python', 'core/main.py']) - time.sleep(5) # sleep for five seconds between bot runs + bot = Popen([executable, 'core/main.py'], stdin=PIPE) + bot.communicate(key) # give the key to core.config.load() + return_code = bot.wait() + if return_code == 1: + exit() # let critical exceptions in the subprocess cause us to + # exit as well + else: + sleep(5) # sleep between bot runs following a non-critical + # subprocess exit if __name__ == "__main__": try: main() except KeyboardInterrupt: - exit("\nKeyboardInterrupt: stopping bot wrapper.") + print "\nKeyboardInterrupt: stopping bot wrapper." From 26e0058ca393b5ad6684be860e9b4c945253381a Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 16 Jun 2011 18:09:28 -0400 Subject: [PATCH 009/692] allow a default value for attribute_to_bool(); rework config.xml structure slightly --- core/config.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/core/config.py b/core/config.py index f7c5785..294d432 100644 --- a/core/config.py +++ b/core/config.py @@ -67,20 +67,21 @@ def make_new_config(): def are_passwords_encrypted(): """Determine if the passwords in our config file are encrypted, returning either True or False.""" - data = _config.getElementsByTagName("config")[0] - element = data.getElementsByTagName("encrypt-passwords")[0] - return attribute_to_bool(element, "enabled") + element = _config.getElementsByTagName("config")[0] + return attribute_to_bool(element, "encrypt-passwords", default=False) -def attribute_to_bool(element, attribute): +def attribute_to_bool(element, attribute, default=None): """Return True if the value of element's attribute is 'true', '1', or 'on'; return False if it is 'false', '0', or 'off' (regardless of - capitalization); raise TypeMismatchException if it does match any of - those.""" + capitalization); return default if it is empty; raise TypeMismatchException + if it does match any of those.""" value = element.getAttribute(attribute).lower() if value in ["true", "1", "on"]: return True elif value in ["false", "0", "off"]: return False + elif value == '': + return default else: e = ("Expected a bool in attribute '{0}' of element '{1}', but " + "got '{2}'.").format(attribute, element.tagName, value) From 7c8d3a33ab78974264669b10b9e868b76fcead8f Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 16 Jun 2011 21:53:42 -0400 Subject: [PATCH 010/692] more config-parsing backbone work; parsing the tag is functional; some other cleanup/changes --- core/config.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++---- core/main.py | 5 ++-- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/core/config.py b/core/config.py index 294d432..8a2831e 100644 --- a/core/config.py +++ b/core/config.py @@ -6,8 +6,12 @@ EarwigBot's XML Config File Parser This handles all tasks involving reading and writing to our config file, including encrypting and decrypting passwords and making a new config file from scratch at the inital bot run. + +Usually you'll just want to do "from core.config import config" and access +config data from within that object. """ +from collections import defaultdict from os import makedirs, path from xml.dom import minidom from xml.parsers.expat import ExpatError @@ -16,15 +20,25 @@ script_dir = path.dirname(path.abspath(__file__)) root_dir = path.split(script_dir)[0] config_path = path.join(root_dir, "config.xml") -_config = None +_config = None # holds the parsed DOM object for our config file +config = None # holds an instance of Container() with our config data class ConfigParseException(Exception): """Base exception for when we could not parse the config file.""" class TypeMismatchException(ConfigParseException): - """A field does not fit to its expected type; e.g., an aribrary string + """A field does not fit to its expected type; e.g., an arbitrary string where we expected a boolean or integer.""" +class MissingElementException(ConfigParseException): + """An element in the config file is missing a required sub-element.""" + +class MissingAttributeException(ConfigParseException): + """An element is missing a required attribute to be parsed correctly.""" + +class Container(object): + """A class to hold information in a nice, accessable manner.""" + def _load_config(): """Load data from our XML config file (config.xml) into a DOM object.""" global _config @@ -42,6 +56,9 @@ def verify_config(): error) exit() else: + if not _config.getElementsByTagName("config"): + e = "Config file is missing a tag." + raise MissingElementException(e) return are_passwords_encrypted() else: print "You haven't configured the bot yet!" @@ -88,8 +105,55 @@ def attribute_to_bool(element, attribute, default=None): raise TypeMismatchException(e) def parse_config(key): - """Parse config data from a DOM object. The key is used to unencrypt - passwords stored in the config file.""" + """Parse config data from a DOM object into the 'config' global variable. + The key is used to unencrypt passwords stored in the XML config file.""" _load_config() # we might be re-loading unnecessarily here, but no harm in # that! data = _config.getElementsByTagName("config")[0] + + cfg = Container() + cfg.components = parse_components(data) + cfg.wiki = parse_wiki(data, key) + cfg.irc = parse_irc(data, key) + cfg.schedule = parse_schedule(data) + cfg.watcher = parse_watcher(data) + + global config + config = cfg + +def parse_components(data): + """Parse everything within the XML tag of our config file. + The components object here will exist as config.components, and is a dict + of our enabled components: components[name] = True if it is enabled, False + if it is disabled.""" + components = defaultdict(lambda: False) # all components are disabled by + # default + element = data.getElementsByTagName("components") + if not element: + e = " is missing a required tag." + raise MissingElementException(e) + element = element[0] # select the first tag out of our list + # of tags, even though we should only have one + + component_tags = element.getElementsByTagName("component") + for component in component_tags: + name = component.getAttribute("name") + if not name: + e = "A tag is missing the required attribute 'name'." + raise MissingAttributeException(e) + is_enabled = attribute_to_bool(component, "enabled", False) + components[name] = is_enabled + + return components + +def parse_wiki(data, key): + pass + +def parse_irc(data, key): + pass + +def parse_schedule(data): + pass + +def parse_watcher(data): + pass diff --git a/core/main.py b/core/main.py index b4e9729..e55d3b9 100644 --- a/core/main.py +++ b/core/main.py @@ -48,7 +48,7 @@ from core import config f_conn = None w_conn = None -def irc_watcher(f_conn): +def irc_watcher(f_conn=None): """Function to handle the IRC watcher as another thread (if frontend and/or scheduler is enabled), otherwise run as the main thread.""" global w_conn @@ -115,7 +115,7 @@ def run(): key = None config.parse_config(key) # load data from the config file and parse it # using the unlock key - components = None + components = config.config.components if components["irc_frontend"]: # make the frontend run on our primary irc_frontend(components) # thread if enabled, and enable additional @@ -138,6 +138,7 @@ def run(): else: # nothing is enabled! print "No bot parts are enabled; stopping..." + exit(1) if __name__ == "__main__": try: From 6869900b65ce89ce6cc7412a69d4e3b34d69da81 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 16 Jun 2011 23:56:39 -0400 Subject: [PATCH 011/692] core/config.py can now parse the tag fully; added some new functions that I pulled out of parse_components(); added stubs for encrypting/decrypting passwords; nitpick in core/main.py --- core/config.py | 124 +++++++++++++++++++++++++++++++++++++++++++++++++-------- core/main.py | 2 +- 2 files changed, 109 insertions(+), 17 deletions(-) diff --git a/core/config.py b/core/config.py index 8a2831e..87cef91 100644 --- a/core/config.py +++ b/core/config.py @@ -81,6 +81,18 @@ def make_new_config(): return is_encrypted +def encrypt_password(password, key): + """If passwords are supposed to be encrypted, use this function to do that + using a user-provided key.""" + # TODO: stub + return password + +def decrypt_password(password, key): + """If passwords are encrypted, use this function to decrypt them using a + user-provided key.""" + # TODO: stub + return password + def are_passwords_encrypted(): """Determine if the passwords in our config file are encrypted, returning either True or False.""" @@ -104,6 +116,34 @@ def attribute_to_bool(element, attribute, default=None): "got '{2}'.").format(attribute, element.tagName, value) raise TypeMismatchException(e) +def get_first_element(parent, tag_name): + """Return the first child of the parent element with the given tag name, or + return None.""" + try: + return parent.getElementsByTagName(tag_name)[0] + except IndexError: + return None + +def get_required_element(parent, tag_name): + """Return the first child of the parent element with the given tag name, or + raise MissingElementException() if no child of that name exists.""" + element = get_first_element(parent, tag_name) + if not element: + e = "<{0}> is missing a required <{1}> tag.".format(parent.tagName, + tag_name) + raise MissingElementException(e) + return element + +def get_required_attribute(element, attr_name): + """Return the value of the attribute 'attr_name' in 'element'. If + undefined, raise MissingAttributeException().""" + attribute = element.getAttribute(attr_name) + if not attribute: + e = "A <{0}> tag is missing the required attribute '{1}'.".format( + element.tagName, attr_name) + raise MissingAttributeException(e) + return attribute + def parse_config(key): """Parse config data from a DOM object into the 'config' global variable. The key is used to unencrypt passwords stored in the XML config file.""" @@ -128,32 +168,84 @@ def parse_components(data): if it is disabled.""" components = defaultdict(lambda: False) # all components are disabled by # default - element = data.getElementsByTagName("components") - if not element: - e = " is missing a required tag." - raise MissingElementException(e) - element = element[0] # select the first tag out of our list - # of tags, even though we should only have one - - component_tags = element.getElementsByTagName("component") - for component in component_tags: - name = component.getAttribute("name") - if not name: - e = "A tag is missing the required attribute 'name'." - raise MissingAttributeException(e) - is_enabled = attribute_to_bool(component, "enabled", False) - components[name] = is_enabled + element = get_required_element(data, "components") + + for component in element.getElementsByTagName("component"): + name = get_required_attribute(component, "name") + components[name] = True return components def parse_wiki(data, key): + """Parse everything within the tag of our XML config file.""" pass + +def parse_irc_server(data, key): + """Parse everything within a tag.""" + server = Container() + connection = get_required_element(data, "connection") + server.host = get_required_attribute(connection, "host") + server.port = get_required_attribute(connection, "port") + server.nick = get_required_attribute(connection, "nick") + server.ident = get_required_attribute(connection, "ident") + server.realname = get_required_attribute(connection, "realname") + + nickserv = get_first_element(data, "nickserv") + if nickserv: + server.nickserv = Container() + server.nickserv.username = get_required_attribute(nickserv, "username") + password = get_required_attribute(nickserv, "password") + if are_passwords_encrypted(): + server.nickserv.password = decrypt_password(password, key) + else: + server.nickserv.password = password + + channels = get_first_element(data, "channels") + if channels: + server.channels = list() + for channel in channels.getElementsByTagName("channel"): + name = get_required_attribute(channel, "name") + server.channels.append(name) + + return server + def parse_irc(data, key): - pass + """Parse everything within the tag of our XML config file.""" + irc = Container() + + element = get_first_element(data, "irc") + if not element: + return irc + + servers = get_first_element(element, "servers") + if servers: + for server in servers.getElementsByTagName("server"): + server_name = get_required_attribute(server, "name") + if server_name == "frontend": + irc.frontend = parse_irc_server(server, key) + elif server_name == "watcher": + irc.watcher = parse_irc_server(server, key) + else: + print ("Warning: config file specifies a with " + + "unknown name '{0}'. Ignoring.").format(server_name) + + permissions = get_first_element(element, "permissions") + if permissions: + irc.permissions = dict() + for group in permissions.getElementsByTagName("group"): + group_name = get_required_attribute(group, "name") + irc.permissions[group_name] = list() + for user in group.getElementsByTagName("user"): + hostname = get_required_attribute(user, "host") + irc.permissions[group_name].append(hostname) + + return irc def parse_schedule(data): + """Parse everything within the tag of our XML config file.""" pass def parse_watcher(data): + """Parse everything within the tag of our XML config file.""" pass diff --git a/core/main.py b/core/main.py index e55d3b9..9f0cc7f 100644 --- a/core/main.py +++ b/core/main.py @@ -136,7 +136,7 @@ def run(): print "Starting IRC watcher..." # component, so run its function only irc_watcher() # and don't worry about anything else - else: # nothing is enabled! + else: # nothing is enabled! print "No bot parts are enabled; stopping..." exit(1) From 94848ab0bc2da42535b78b3991a4b6aa87ddcf99 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Fri, 17 Jun 2011 00:10:02 -0400 Subject: [PATCH 012/692] wrap parse_config() to catch ConfigParseExceptions and report them to the user cleanly; some minor doc changes. --- core/config.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/core/config.py b/core/config.py index 87cef91..2169481 100644 --- a/core/config.py +++ b/core/config.py @@ -118,7 +118,7 @@ def attribute_to_bool(element, attribute, default=None): def get_first_element(parent, tag_name): """Return the first child of the parent element with the given tag name, or - return None.""" + return None if no child of that name exists.""" try: return parent.getElementsByTagName(tag_name)[0] except IndexError: @@ -129,8 +129,8 @@ def get_required_element(parent, tag_name): raise MissingElementException() if no child of that name exists.""" element = get_first_element(parent, tag_name) if not element: - e = "<{0}> is missing a required <{1}> tag.".format(parent.tagName, - tag_name) + e = "A <{0}> tag is missing a required <{1}> child tag.".format( + parent.tagName, tag_name) raise MissingElementException(e) return element @@ -145,6 +145,16 @@ def get_required_attribute(element, attr_name): return attribute def parse_config(key): + """A thin wrapper for the actual config parser in _parse_config(): catch + parsing exceptions and report them to the user cleanly.""" + try: + _parse_config(key) + except ConfigParseException as e: + print "\nError parsing config file:" + print e + exit(1) + +def _parse_config(key): """Parse config data from a DOM object into the 'config' global variable. The key is used to unencrypt passwords stored in the XML config file.""" _load_config() # we might be re-loading unnecessarily here, but no harm in From 369b60b823a4b5e89a32fd1c310b10e4664cb777 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Fri, 17 Jun 2011 19:32:55 -0400 Subject: [PATCH 013/692] adding Cryptography() IRC command class with hash functions via hashlib --- irc/commands/crypt.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 irc/commands/crypt.py diff --git a/irc/commands/crypt.py b/irc/commands/crypt.py new file mode 100644 index 0000000..29fcd21 --- /dev/null +++ b/irc/commands/crypt.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- + +# Cryptography functions (hashing and cyphers). + +import hashlib + +from irc.base_command import BaseCommand + +class Calc(BaseCommand): + def get_hooks(self): + return ["msg"] + + def get_help(self, command): + if command == "hash": + return ("Return the hash of a string using a given algorithm, " + + "e.g. '!hash sha512 Hello world!'.") + else: + return ("{0} a string with a given key using a given algorithm, " + + "e.g. '!{1} blowfish some_key Hello world!'.").format( + command.capitalize(), command) + + def check(self, data): + if data.is_command and data.command in ["hash", "encrypt", "decrypt"]: + return True + return False + + def process(self, data): + if not data.args: + self.connection.reply(data, "what do you want me to do?") + return + + if data.command == "hash": + algo = data.args[0] + if algo in hashlib.algorithms: + string = ' '.join(data.args[1:]) + result = eval("hashlib.{0}(string)".format(algo)).hexdigest() + self.connection.reply(data, result) + else: + self.connection.reply(data, "unknown algorithm: {0}".format( + algo)) + + else: + self.connection.reply(data, "not implemented yet!") From 02b8fbdd1b4f3295d4809096d8635a909321ebfa Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 18 Jun 2011 00:12:06 -0400 Subject: [PATCH 014/692] ugh I am an idiot --- irc/commands/crypt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/irc/commands/crypt.py b/irc/commands/crypt.py index 29fcd21..8f60720 100644 --- a/irc/commands/crypt.py +++ b/irc/commands/crypt.py @@ -6,7 +6,7 @@ import hashlib from irc.base_command import BaseCommand -class Calc(BaseCommand): +class Cryptography(BaseCommand): def get_hooks(self): return ["msg"] From 1e89d2a06f4250437298d95a084636cd32c45a0e Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 18 Jun 2011 01:38:23 -0400 Subject: [PATCH 015/692] new blowfish.py module, some changes in Cryptography(), LICENSE cleanup --- LICENSE | 3 +- irc/commands/crypt.py | 36 +++- lib/blowfish.py | 493 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 522 insertions(+), 10 deletions(-) create mode 100644 lib/blowfish.py diff --git a/LICENSE b/LICENSE index e9a8be1..5ebac08 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,4 @@ -Copyright (c) 2009-2011 Ben Kurtovic (The Earwig) - +Copyright (C) 2009, 2010, 2011 by Ben Kurtovic Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/irc/commands/crypt.py b/irc/commands/crypt.py index 8f60720..506a714 100644 --- a/irc/commands/crypt.py +++ b/irc/commands/crypt.py @@ -5,6 +5,7 @@ import hashlib from irc.base_command import BaseCommand +from lib import blowfish class Cryptography(BaseCommand): def get_hooks(self): @@ -13,11 +14,16 @@ class Cryptography(BaseCommand): def get_help(self, command): if command == "hash": return ("Return the hash of a string using a given algorithm, " + - "e.g. '!hash sha512 Hello world!'.") + "e.g. '!hash sha512 Hello world!'. Use '!hash list' for " + + "a list of supported algorithms.") + elif command == "encrypt": + return ("Encrypt any string with a given key using an " + + "implementation of Blowfish, e.g. '!encrypt some_key " + + "Hello world!'.") else: - return ("{0} a string with a given key using a given algorithm, " + - "e.g. '!{1} blowfish some_key Hello world!'.").format( - command.capitalize(), command) + return ("Decrypt a string with a given key using a given " + + "algorithm, e.g. '!decrypt blowfish some_key Hello " + + "world!'.") def check(self, data): if data.is_command and data.command in ["hash", "encrypt", "decrypt"]: @@ -26,18 +32,32 @@ class Cryptography(BaseCommand): def process(self, data): if not data.args: - self.connection.reply(data, "what do you want me to do?") + self.connection.reply(data, "what do you want me to {0}?".format( + data.command)) return if data.command == "hash": algo = data.args[0] - if algo in hashlib.algorithms: + if algo == "list": + algos = ', '.join(hashlib.algorithms) + self.connection.reply(data, "supported algorithms: " + algos + + ".") + elif algo in hashlib.algorithms: string = ' '.join(data.args[1:]) result = eval("hashlib.{0}(string)".format(algo)).hexdigest() self.connection.reply(data, result) else: - self.connection.reply(data, "unknown algorithm: {0}".format( + self.connection.reply(data, "unknown algorithm: '{0}'.".format( algo)) else: - self.connection.reply(data, "not implemented yet!") + key = data.args[0] + text = ' '.join(data.args[1:]) + if not text: + self.connection.reply(data, "that's a key, yes, but what do " + + " you want me to {0}?".format(data.command)) + return + if data.command == "encrypt": + self.connection.reply(data, blowfish.encrypt(key, text)) + else: + self.connection.reply(data, blowfish.decrypt(key, text)) diff --git a/lib/blowfish.py b/lib/blowfish.py new file mode 100644 index 0000000..d3bd3a3 --- /dev/null +++ b/lib/blowfish.py @@ -0,0 +1,493 @@ +# +# blowfish.py +# Copyright (C) 2002 Michael Gilfix +# +# This module is open source; you can redistribute it and/or +# modify it under the terms of the GPL or Artistic License. +# These licenses are available at http://www.opensource.org +# +# This software must be used and distributed in accordance +# with the law. The author claims no liability for its +# misuse. +# +# 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. +# + +""" +Blowfish Encryption + +This module is a pure python implementation of Bruce Schneier's +encryption scheme 'Blowfish'. Blowish is a 16-round Feistel Network +cipher and offers substantial speed gains over DES. + +The key is a string of length anywhere between 64 and 448 bits, or +equivalently 8 and 56 bytes. The encryption and decryption functions operate +on 64-bit blocks, or 8 byte strings. + +Send questions, comments, bugs my way: + Michael Gilfix +""" + +__author__ = "Michael Gilfix " + +class Blowfish: + + """Blowfish encryption Scheme + + This class implements the encryption and decryption + functionality of the Blowfish cipher. + + Public functions: + + def __init__ (self, key) + Creates an instance of blowfish using 'key' + as the encryption key. Key is a string of + length ranging from 8 to 56 bytes (64 to 448 + bits). Once the instance of the object is + created, the key is no longer necessary. + + def encrypt (self, data): + Encrypt an 8 byte (64-bit) block of text + where 'data' is an 8 byte string. Returns an + 8-byte encrypted string. + + def decrypt (self, data): + Decrypt an 8 byte (64-bit) encrypted block + of text, where 'data' is the 8 byte encrypted + string. Returns an 8-byte string of plaintext. + + def cipher (self, xl, xr, direction): + Encrypts a 64-bit block of data where xl is + the upper 32-bits and xr is the lower 32-bits. + 'direction' is the direction to apply the + cipher, either ENCRYPT or DECRYPT constants. + returns a tuple of either encrypted or decrypted + data of the left half and right half of the + 64-bit block. + + Private members: + + def __round_func (self, xl) + Performs an obscuring function on the 32-bit + block of data 'xl', which is the left half of + the 64-bit block of data. Returns the 32-bit + result as a long integer. + + """ + + # Cipher directions + ENCRYPT = 0 + DECRYPT = 1 + + # For the __round_func + modulus = long (2) ** 32 + + def __init__ (self, key): + + if not key or len (key) < 8 or len (key) > 56: + raise RuntimeError, "Attempted to initialize Blowfish cipher with key of invalid length: %s" %len (key) + + self.p_boxes = [ + 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, + 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, + 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, + 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, + 0x9216D5D9, 0x8979FB1B + ] + + self.s_boxes = [ + [ + 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, + 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, + 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, + 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, + 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, + 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, + 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, + 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, + 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, + 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, + 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, + 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, + 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, + 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, + 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, + 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, + 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, + 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, + 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, + 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, + 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, + 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, + 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, + 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, + 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, + 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, + 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, + 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, + 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, + 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, + 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, + 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, + 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, + 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, + 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, + 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, + 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, + 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, + 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, + 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, + 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, + 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, + 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, + 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, + 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, + 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, + 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, + 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, + 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, + 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, + 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, + 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, + 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, + 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, + 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, + 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, + 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, + 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, + 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, + 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, + 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, + 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, + 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, + 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A + ], + [ + 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, + 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, + 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, + 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, + 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, + 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, + 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, + 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, + 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, + 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, + 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, + 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, + 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, + 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, + 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, + 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, + 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, + 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, + 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, + 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, + 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, + 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, + 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, + 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, + 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, + 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, + 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, + 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, + 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, + 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, + 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, + 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, + 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, + 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, + 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, + 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, + 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, + 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, + 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, + 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, + 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, + 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, + 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, + 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, + 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, + 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, + 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, + 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, + 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, + 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, + 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, + 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, + 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, + 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, + 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, + 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, + 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, + 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, + 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, + 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, + 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, + 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, + 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, + 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 + ], + [ + 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, + 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, + 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, + 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, + 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, + 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, + 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, + 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, + 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, + 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, + 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, + 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, + 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, + 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, + 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, + 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, + 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, + 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, + 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, + 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, + 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, + 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, + 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, + 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, + 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, + 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, + 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, + 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, + 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, + 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, + 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, + 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, + 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, + 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, + 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, + 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, + 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, + 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, + 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, + 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, + 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, + 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, + 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, + 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, + 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, + 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, + 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, + 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, + 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, + 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, + 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, + 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, + 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, + 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, + 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, + 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, + 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, + 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, + 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, + 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, + 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, + 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, + 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, + 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 + ], + [ + 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, + 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, + 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, + 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, + 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, + 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, + 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, + 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, + 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, + 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, + 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, + 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, + 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, + 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, + 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, + 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, + 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, + 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, + 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, + 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, + 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, + 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, + 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, + 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, + 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, + 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, + 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, + 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, + 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, + 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, + 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, + 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, + 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, + 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, + 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, + 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, + 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, + 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, + 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, + 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, + 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, + 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, + 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, + 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, + 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, + 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, + 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, + 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, + 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, + 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, + 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, + 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, + 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, + 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, + 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, + 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, + 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, + 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, + 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, + 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, + 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, + 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, + 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, + 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 + ] + ] + + # Cycle through the p-boxes and round-robin XOR the + # key with the p-boxes + key_len = len (key) + index = 0 + for i in range (len (self.p_boxes)): + val = (ord (key[index % key_len]) << 24) + \ + (ord (key[(index + 1) % key_len]) << 16) + \ + (ord (key[(index + 2) % key_len]) << 8) + \ + ord (key[(index + 3) % key_len]) + self.p_boxes[i] = self.p_boxes[i] ^ val + index = index + 4 + + # For the chaining process + l, r = 0, 0 + + # Begin chain replacing the p-boxes + for i in range (0, len (self.p_boxes), 2): + l, r = self.cipher (l, r, self.ENCRYPT) + self.p_boxes[i] = l + self.p_boxes[i + 1] = r + + # Chain replace the s-boxes + for i in range (len (self.s_boxes)): + for j in range (0, len (self.s_boxes[i]), 2): + l, r = self.cipher (l, r, self.ENCRYPT) + self.s_boxes[i][j] = l + self.s_boxes[i][j + 1] = r + + def cipher (self, xl, xr, direction): + + if direction == self.ENCRYPT: + for i in range (16): + xl = xl ^ self.p_boxes[i] + xr = self.__round_func (xl) ^ xr + xl, xr = xr, xl + xl, xr = xr, xl + xr = xr ^ self.p_boxes[16] + xl = xl ^ self.p_boxes[17] + else: + for i in range (17, 1, -1): + xl = xl ^ self.p_boxes[i] + xr = self.__round_func (xl) ^ xr + xl, xr = xr, xl + xl, xr = xr, xl + xr = xr ^ self.p_boxes[1] + xl = xl ^ self.p_boxes[0] + return xl, xr + + def __round_func (self, xl): + a = (xl & 0xFF000000) >> 24 + b = (xl & 0x00FF0000) >> 16 + c = (xl & 0x0000FF00) >> 8 + d = xl & 0x000000FF + + # Perform all ops as longs then and out the last 32-bits to + # obtain the integer + f = (long (self.s_boxes[0][a]) + long (self.s_boxes[1][b])) % self.modulus + f = f ^ long (self.s_boxes[2][c]) + f = f + long (self.s_boxes[3][d]) + f = (f % self.modulus) & 0xFFFFFFFF + + return f + + def encrypt (self, data): + + if not len (data) == 8: + raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) + + # Use big endianess since that's what everyone else uses + xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) + xr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) + + cl, cr = self.cipher (xl, xr, self.ENCRYPT) + chars = ''.join ([ + chr ((cl >> 24) & 0xFF), chr ((cl >> 16) & 0xFF), chr ((cl >> 8) & 0xFF), chr (cl & 0xFF), + chr ((cr >> 24) & 0xFF), chr ((cr >> 16) & 0xFF), chr ((cr >> 8) & 0xFF), chr (cr & 0xFF) + ]) + return chars + + def decrypt (self, data): + + if not len (data) == 8: + raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) + + # Use big endianess since that's what everyone else uses + cl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) + cr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) + + xl, xr = self.cipher (cl, cr, self.DECRYPT) + chars = ''.join ([ + chr ((xl >> 24) & 0xFF), chr ((xl >> 16) & 0xFF), chr ((xl >> 8) & 0xFF), chr (xl & 0xFF), + chr ((xr >> 24) & 0xFF), chr ((xr >> 16) & 0xFF), chr ((xr >> 8) & 0xFF), chr (xr & 0xFF) + ]) + return chars + + def blocksize (self): + return 8 + + def key_length (self): + return 56 + + def key_bits (self): + return 56 * 8 + +############################################################## +# Module testing + +if __name__ == '__main__': + key = 'This is a test key' + cipher = Blowfish (key) + + print "Testing encryption:" + xl = 123456 + xr = 654321 + print "\tPlain text: (%s, %s)" %(xl, xr) + cl, cr = cipher.cipher (xl, xr, cipher.ENCRYPT) + print "\tCrypted is: (%s, %s)" %(cl, cr) + dl, dr = cipher.cipher (cl, cr, cipher.DECRYPT) + print "\tUnencrypted is: (%s, %s)" %(dl, dr) + + print "Testing buffer encrypt:" + text = 'testtest' + print "\tText: %s" %text + crypted = cipher.encrypt (text) + print "\tEncrypted: %s" %crypted + decrypted = cipher.decrypt (crypted) + print "\tDecrypted: %s" %decrypted From f90167e8e72a98be49ea4b70881e5dc64935d6fa Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 18 Jun 2011 18:27:29 -0400 Subject: [PATCH 016/692] blowfish.encrypt(key, plaintext), blowfish.decrypt(key, cyphertext); clean up certain things; 'python lib/blowfish.py' is interactive; implement blowfish in Cryptography() --- irc/commands/crypt.py | 35 +- lib/__init__.py | 0 lib/blowfish.py | 1012 ++++++++++++++++++++++++++----------------------- 3 files changed, 568 insertions(+), 479 deletions(-) create mode 100644 lib/__init__.py diff --git a/irc/commands/crypt.py b/irc/commands/crypt.py index 506a714..92793d3 100644 --- a/irc/commands/crypt.py +++ b/irc/commands/crypt.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- -# Cryptography functions (hashing and cyphers). +""" +Cryptography functions (hashing and cyphers) for EarwigBot IRC. +""" import hashlib @@ -19,11 +21,11 @@ class Cryptography(BaseCommand): elif command == "encrypt": return ("Encrypt any string with a given key using an " + "implementation of Blowfish, e.g. '!encrypt some_key " + - "Hello world!'.") + "Hello!'.") else: - return ("Decrypt a string with a given key using a given " + - "algorithm, e.g. '!decrypt blowfish some_key Hello " + - "world!'.") + return ("Decrypt any string with a given key using an " + + "implementation of Blowfish, e.g. '!decrypt some_key " + + "762cee8a5239548af18275d6c1184f16'.") def check(self, data): if data.is_command and data.command in ["hash", "encrypt", "decrypt"]: @@ -53,11 +55,24 @@ class Cryptography(BaseCommand): else: key = data.args[0] text = ' '.join(data.args[1:]) + if not text: - self.connection.reply(data, "that's a key, yes, but what do " + - " you want me to {0}?".format(data.command)) + self.connection.reply(data, ("a key was provided, but text " + + "to {0} was not.").format(data.command)) return - if data.command == "encrypt": - self.connection.reply(data, blowfish.encrypt(key, text)) + + try: + if data.command == "encrypt": + result = blowfish.encrypt(key, text) + else: + result = blowfish.decrypt(key, text) + except blowfish.KeyTooShortError: + self.connection.reply(data, "key is too short.") + except blowfish.KeyTooLongError: + self.connection.reply(data, "key is too long.") + except blowfish.IncorrectKeyError: + self.connection.reply(data, "key is incorrect!") + except blowfish.BadCyphertextError as e: + self.connection.reply(data, "bad cyphertext: {0}.".format(e)) else: - self.connection.reply(data, blowfish.decrypt(key, text)) + self.connection.reply(data, result) diff --git a/lib/__init__.py b/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lib/blowfish.py b/lib/blowfish.py index d3bd3a3..8a5e5f2 100644 --- a/lib/blowfish.py +++ b/lib/blowfish.py @@ -1,6 +1,8 @@ +# -*- coding: utf-8 -*- # # blowfish.py # Copyright (C) 2002 Michael Gilfix +# Copyright (C) 2011 Ben Kurtovic # # This module is open source; you can redistribute it and/or # modify it under the terms of the GPL or Artistic License. @@ -18,476 +20,548 @@ """ Blowfish Encryption -This module is a pure python implementation of Bruce Schneier's -encryption scheme 'Blowfish'. Blowish is a 16-round Feistel Network -cipher and offers substantial speed gains over DES. - -The key is a string of length anywhere between 64 and 448 bits, or -equivalently 8 and 56 bytes. The encryption and decryption functions operate -on 64-bit blocks, or 8 byte strings. - -Send questions, comments, bugs my way: - Michael Gilfix +This module is a pure python implementation of Bruce Schneier's encryption +scheme 'Blowfish'. Blowish is a 16-round Feistel Network cipher and offers +substantial speed gains over DES. + +The key is a string of length anywhere between 64 and 448 bits, or equivalently +8 and 56 bytes. The encryption and decryption functions operate on 64-bit +blocks, or 8 byte strings. + +The entire Blowfish() class (excluding verify_key()) is by Michael Gilfix +. + +Blowfish.verify_key(), exception classes, encrypt() and decrypt() wrappers, and +interactive mode are by Ben Kurtovic . + +Map of exceptions: + * BlowfishError + * BlockSizeError + * KeyLengthError + * KeyTooShortError + * KeyTooLongError + * DecryptionError + * IncorrectKeyError + * BadCyphertextError """ -__author__ = "Michael Gilfix " - -class Blowfish: - - """Blowfish encryption Scheme - - This class implements the encryption and decryption - functionality of the Blowfish cipher. - - Public functions: - - def __init__ (self, key) - Creates an instance of blowfish using 'key' - as the encryption key. Key is a string of - length ranging from 8 to 56 bytes (64 to 448 - bits). Once the instance of the object is - created, the key is no longer necessary. - - def encrypt (self, data): - Encrypt an 8 byte (64-bit) block of text - where 'data' is an 8 byte string. Returns an - 8-byte encrypted string. - - def decrypt (self, data): - Decrypt an 8 byte (64-bit) encrypted block - of text, where 'data' is the 8 byte encrypted - string. Returns an 8-byte string of plaintext. - - def cipher (self, xl, xr, direction): - Encrypts a 64-bit block of data where xl is - the upper 32-bits and xr is the lower 32-bits. - 'direction' is the direction to apply the - cipher, either ENCRYPT or DECRYPT constants. - returns a tuple of either encrypted or decrypted - data of the left half and right half of the - 64-bit block. - - Private members: - - def __round_func (self, xl) - Performs an obscuring function on the 32-bit - block of data 'xl', which is the left half of - the 64-bit block of data. Returns the 32-bit - result as a long integer. - - """ - - # Cipher directions - ENCRYPT = 0 - DECRYPT = 1 - - # For the __round_func - modulus = long (2) ** 32 - - def __init__ (self, key): - - if not key or len (key) < 8 or len (key) > 56: - raise RuntimeError, "Attempted to initialize Blowfish cipher with key of invalid length: %s" %len (key) - - self.p_boxes = [ - 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, - 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, - 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, - 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, - 0x9216D5D9, 0x8979FB1B - ] - - self.s_boxes = [ - [ - 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, - 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, - 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, - 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, - 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, - 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, - 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, - 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, - 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, - 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, - 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, - 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, - 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, - 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, - 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, - 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, - 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, - 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, - 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, - 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, - 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, - 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, - 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, - 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, - 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, - 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, - 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, - 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, - 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, - 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, - 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, - 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, - 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, - 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, - 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, - 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, - 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, - 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, - 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, - 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, - 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, - 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, - 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, - 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, - 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, - 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, - 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, - 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, - 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, - 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, - 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, - 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, - 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, - 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, - 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, - 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, - 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, - 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, - 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, - 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, - 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, - 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, - 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, - 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A - ], - [ - 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, - 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, - 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, - 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, - 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, - 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, - 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, - 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, - 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, - 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, - 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, - 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, - 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, - 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, - 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, - 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, - 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, - 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, - 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, - 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, - 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, - 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, - 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, - 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, - 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, - 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, - 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, - 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, - 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, - 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, - 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, - 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, - 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, - 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, - 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, - 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, - 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, - 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, - 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, - 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, - 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, - 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, - 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, - 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, - 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, - 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, - 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, - 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, - 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, - 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, - 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, - 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, - 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, - 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, - 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, - 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, - 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, - 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, - 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, - 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, - 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, - 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, - 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, - 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 - ], - [ - 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, - 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, - 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, - 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, - 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, - 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, - 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, - 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, - 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, - 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, - 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, - 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, - 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, - 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, - 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, - 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, - 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, - 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, - 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, - 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, - 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, - 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, - 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, - 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, - 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, - 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, - 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, - 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, - 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, - 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, - 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, - 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, - 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, - 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, - 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, - 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, - 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, - 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, - 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, - 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, - 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, - 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, - 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, - 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, - 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, - 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, - 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, - 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, - 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, - 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, - 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, - 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, - 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, - 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, - 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, - 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, - 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, - 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, - 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, - 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, - 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, - 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, - 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, - 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 - ], - [ - 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, - 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, - 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, - 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, - 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, - 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, - 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, - 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, - 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, - 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, - 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, - 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, - 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, - 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, - 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, - 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, - 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, - 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, - 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, - 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, - 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, - 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, - 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, - 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, - 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, - 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, - 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, - 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, - 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, - 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, - 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, - 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, - 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, - 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, - 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, - 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, - 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, - 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, - 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, - 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, - 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, - 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, - 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, - 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, - 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, - 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, - 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, - 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, - 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, - 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, - 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, - 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, - 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, - 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, - 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, - 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, - 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, - 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, - 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, - 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, - 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, - 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, - 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, - 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 - ] - ] - - # Cycle through the p-boxes and round-robin XOR the - # key with the p-boxes - key_len = len (key) - index = 0 - for i in range (len (self.p_boxes)): - val = (ord (key[index % key_len]) << 24) + \ - (ord (key[(index + 1) % key_len]) << 16) + \ - (ord (key[(index + 2) % key_len]) << 8) + \ - ord (key[(index + 3) % key_len]) - self.p_boxes[i] = self.p_boxes[i] ^ val - index = index + 4 - - # For the chaining process - l, r = 0, 0 - - # Begin chain replacing the p-boxes - for i in range (0, len (self.p_boxes), 2): - l, r = self.cipher (l, r, self.ENCRYPT) - self.p_boxes[i] = l - self.p_boxes[i + 1] = r - - # Chain replace the s-boxes - for i in range (len (self.s_boxes)): - for j in range (0, len (self.s_boxes[i]), 2): - l, r = self.cipher (l, r, self.ENCRYPT) - self.s_boxes[i][j] = l - self.s_boxes[i][j + 1] = r - - def cipher (self, xl, xr, direction): - - if direction == self.ENCRYPT: - for i in range (16): - xl = xl ^ self.p_boxes[i] - xr = self.__round_func (xl) ^ xr - xl, xr = xr, xl - xl, xr = xr, xl - xr = xr ^ self.p_boxes[16] - xl = xl ^ self.p_boxes[17] - else: - for i in range (17, 1, -1): - xl = xl ^ self.p_boxes[i] - xr = self.__round_func (xl) ^ xr - xl, xr = xr, xl - xl, xr = xr, xl - xr = xr ^ self.p_boxes[1] - xl = xl ^ self.p_boxes[0] - return xl, xr - - def __round_func (self, xl): - a = (xl & 0xFF000000) >> 24 - b = (xl & 0x00FF0000) >> 16 - c = (xl & 0x0000FF00) >> 8 - d = xl & 0x000000FF - - # Perform all ops as longs then and out the last 32-bits to - # obtain the integer - f = (long (self.s_boxes[0][a]) + long (self.s_boxes[1][b])) % self.modulus - f = f ^ long (self.s_boxes[2][c]) - f = f + long (self.s_boxes[3][d]) - f = (f % self.modulus) & 0xFFFFFFFF - - return f - - def encrypt (self, data): - - if not len (data) == 8: - raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) - - # Use big endianess since that's what everyone else uses - xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) - xr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) - - cl, cr = self.cipher (xl, xr, self.ENCRYPT) - chars = ''.join ([ - chr ((cl >> 24) & 0xFF), chr ((cl >> 16) & 0xFF), chr ((cl >> 8) & 0xFF), chr (cl & 0xFF), - chr ((cr >> 24) & 0xFF), chr ((cr >> 16) & 0xFF), chr ((cr >> 8) & 0xFF), chr (cr & 0xFF) - ]) - return chars - - def decrypt (self, data): - - if not len (data) == 8: - raise RuntimeError, "Attempted to encrypt data of invalid block length: %s" %len (data) - - # Use big endianess since that's what everyone else uses - cl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) - cr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) - - xl, xr = self.cipher (cl, cr, self.DECRYPT) - chars = ''.join ([ - chr ((xl >> 24) & 0xFF), chr ((xl >> 16) & 0xFF), chr ((xl >> 8) & 0xFF), chr (xl & 0xFF), - chr ((xr >> 24) & 0xFF), chr ((xr >> 16) & 0xFF), chr ((xr >> 8) & 0xFF), chr (xr & 0xFF) - ]) - return chars - - def blocksize (self): - return 8 - - def key_length (self): - return 56 - - def key_bits (self): - return 56 * 8 - -############################################################## -# Module testing +class BlowfishError(Exception): + """Base exception class for errors involving blowfish + encryption/decryption.""" + +class BlockSizeError(BlowfishError): + """Attempted to handle a block not 8 bytes in length.""" + +class KeyLengthError(BlowfishError): + """Base class for invalid key length exceptions.""" + +class KeyTooShortError(KeyLengthError): + """The given key is too short: it is less than 8 bytes (64 bits).""" + +class KeyTooLongError(KeyLengthError): + """The given key is too long: it is more than 56 bytes (448 bits.""" + +class DecryptionError(BlowfishError): + """Base class for exceptions that occur during decryption only.""" + +class IncorrectKeyError(DecryptionError): + """Attempted to decrypt something with the wrong key.""" + +class BadCyphertextError(DecryptionError): + """The given cyphertext is malformed and cannot be decrypted.""" + +class Blowfish(object): + """Blowfish encryption Scheme + + This class implements the encryption and decryption + functionality of the Blowfish cipher. + + Public functions: + + def __init__ (self, key) + Creates an instance of blowfish using 'key' + as the encryption key. Key is a string of + length ranging from 8 to 56 bytes (64 to 448 + bits). Once the instance of the object is + created, the key is no longer necessary. + + def encrypt (self, data): + Encrypt an 8 byte (64-bit) block of text + where 'data' is an 8 byte string. Returns an + 8-byte encrypted string. + + def decrypt (self, data): + Decrypt an 8 byte (64-bit) encrypted block + of text, where 'data' is the 8 byte encrypted + string. Returns an 8-byte string of plaintext. + + def cipher (self, xl, xr, direction): + Encrypts a 64-bit block of data where xl is + the upper 32-bits and xr is the lower 32-bits. + 'direction' is the direction to apply the + cipher, either ENCRYPT or DECRYPT constants. + returns a tuple of either encrypted or decrypted + data of the left half and right half of the + 64-bit block. + + Private members: + + def __round_func (self, xl) + Performs an obscuring function on the 32-bit + block of data 'xl', which is the left half of + the 64-bit block of data. Returns the 32-bit + result as a long integer. + """ + + # Cipher directions + ENCRYPT = 0 + DECRYPT = 1 + + # For the __round_func + modulus = long (2) ** 32 + + def __init__ (self, key): + self.verify_key(key) + + self.p_boxes = [ + 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, + 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, + 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, + 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, + 0x9216D5D9, 0x8979FB1B + ] + + self.s_boxes = [ + [ + 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, + 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, + 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, + 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, + 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, + 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, + 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, + 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, + 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, + 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, + 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, + 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, + 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, + 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, + 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, + 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, + 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, + 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, + 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, + 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, + 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, + 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, + 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, + 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, + 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, + 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, + 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, + 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, + 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, + 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, + 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, + 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, + 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, + 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, + 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, + 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, + 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, + 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, + 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, + 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, + 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, + 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, + 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, + 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, + 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, + 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, + 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, + 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, + 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, + 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, + 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, + 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, + 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, + 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, + 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, + 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, + 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, + 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, + 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, + 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, + 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, + 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, + 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, + 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A + ], + [ + 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, + 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, + 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, + 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, + 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, + 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, + 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, + 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, + 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, + 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, + 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, + 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, + 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, + 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, + 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, + 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, + 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, + 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, + 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, + 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, + 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, + 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, + 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, + 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, + 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, + 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, + 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, + 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, + 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, + 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, + 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, + 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, + 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, + 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, + 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, + 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, + 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, + 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, + 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, + 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, + 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, + 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, + 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, + 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, + 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, + 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, + 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, + 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, + 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, + 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, + 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, + 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, + 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, + 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, + 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, + 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, + 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, + 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, + 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, + 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, + 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, + 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, + 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, + 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 + ], + [ + 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, + 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, + 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, + 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, + 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, + 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, + 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, + 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, + 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, + 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, + 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, + 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, + 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, + 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, + 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, + 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, + 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, + 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, + 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, + 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, + 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, + 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, + 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, + 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, + 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, + 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, + 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, + 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, + 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, + 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, + 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, + 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, + 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, + 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, + 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, + 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, + 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, + 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, + 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, + 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, + 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, + 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, + 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, + 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, + 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, + 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, + 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, + 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, + 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, + 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, + 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, + 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, + 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, + 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, + 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, + 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, + 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, + 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, + 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, + 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, + 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, + 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, + 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, + 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 + ], + [ + 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, + 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, + 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, + 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, + 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, + 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, + 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, + 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, + 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, + 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, + 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, + 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, + 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, + 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, + 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, + 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, + 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, + 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, + 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, + 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, + 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, + 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, + 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, + 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, + 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, + 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, + 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, + 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, + 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, + 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, + 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, + 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, + 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, + 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, + 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, + 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, + 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, + 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, + 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, + 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, + 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, + 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, + 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, + 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, + 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, + 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, + 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, + 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, + 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, + 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, + 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, + 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, + 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, + 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, + 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, + 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, + 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, + 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, + 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, + 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, + 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, + 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, + 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, + 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 + ] + ] + + # Cycle through the p-boxes and round-robin XOR the + # key with the p-boxes + key_len = len (key) + index = 0 + for i in range (len (self.p_boxes)): + val = (ord (key[index % key_len]) << 24) + \ + (ord (key[(index + 1) % key_len]) << 16) + \ + (ord (key[(index + 2) % key_len]) << 8) + \ + ord (key[(index + 3) % key_len]) + self.p_boxes[i] = self.p_boxes[i] ^ val + index = index + 4 + + # For the chaining process + l, r = 0, 0 + + # Begin chain replacing the p-boxes + for i in range (0, len (self.p_boxes), 2): + l, r = self.cipher (l, r, self.ENCRYPT) + self.p_boxes[i] = l + self.p_boxes[i + 1] = r + + # Chain replace the s-boxes + for i in range (len (self.s_boxes)): + for j in range (0, len (self.s_boxes[i]), 2): + l, r = self.cipher (l, r, self.ENCRYPT) + self.s_boxes[i][j] = l + self.s_boxes[i][j + 1] = r + + def cipher(self, xl, xr, direction): + if direction == self.ENCRYPT: + for i in range (16): + xl = xl ^ self.p_boxes[i] + xr = self.__round_func (xl) ^ xr + xl, xr = xr, xl + xl, xr = xr, xl + xr = xr ^ self.p_boxes[16] + xl = xl ^ self.p_boxes[17] + else: + for i in range (17, 1, -1): + xl = xl ^ self.p_boxes[i] + xr = self.__round_func (xl) ^ xr + xl, xr = xr, xl + xl, xr = xr, xl + xr = xr ^ self.p_boxes[1] + xl = xl ^ self.p_boxes[0] + return xl, xr + + def __round_func(self, xl): + a = (xl & 0xFF000000) >> 24 + b = (xl & 0x00FF0000) >> 16 + c = (xl & 0x0000FF00) >> 8 + d = xl & 0x000000FF + + # Perform all ops as longs then and out the last 32-bits to + # obtain the integer + f = (long (self.s_boxes[0][a]) + long (self.s_boxes[1][b])) % self.modulus + f = f ^ long (self.s_boxes[2][c]) + f = f + long (self.s_boxes[3][d]) + f = (f % self.modulus) & 0xFFFFFFFF + + return f + + def encrypt(self, data): + if not len(data) == 8: + raise BlockSizeError("{0} != 8".format(len(data))) + + # Use big endianess since that's what everyone else uses + xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) + xr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) + + cl, cr = self.cipher (xl, xr, self.ENCRYPT) + chars = ''.join ([ + chr ((cl >> 24) & 0xFF), chr ((cl >> 16) & 0xFF), chr ((cl >> 8) & 0xFF), chr (cl & 0xFF), + chr ((cr >> 24) & 0xFF), chr ((cr >> 16) & 0xFF), chr ((cr >> 8) & 0xFF), chr (cr & 0xFF) + ]) + return chars + + def decrypt(self, data): + if not len(data) == 8: + raise BlockSizeError("{0} != 8".format(len(data))) + + # Use big endianess since that's what everyone else uses + cl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) + cr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24) + + xl, xr = self.cipher (cl, cr, self.DECRYPT) + chars = ''.join ([ + chr ((xl >> 24) & 0xFF), chr ((xl >> 16) & 0xFF), chr ((xl >> 8) & 0xFF), chr (xl & 0xFF), + chr ((xr >> 24) & 0xFF), chr ((xr >> 16) & 0xFF), chr ((xr >> 8) & 0xFF), chr (xr & 0xFF) + ]) + return chars + + def blocksize(self): + return 8 + + def key_length(self): + return 56 + + def key_bits(self): + return 56 * 8 + + def verify_key(self, key): + """Make sure our key is not too short or too long; if there's a + problem, raise KeyTooShortError() or KeyTooLongError().""" + if not key: + raise KeyTooShortError("no key given") + if len(key) < 8: + raise KeyTooShortError("{0} < 8".format(len(key))) + if len(key) > 56: + raise KeyTooLongError("{0} > 56".format(len(key))) + +def encrypt(key, plaintext): + """Encrypt any length of plaintext using a given key that must be between + 8 and 56 bytes in length. This is a convienence function that can handle + plaintext that is not a single block in length. It will auto-pad blocks + that are less than 8 bytes with spaces that are automatically removed by + decrypt(). Actual spaces in plaintext are preserved.""" + cypher = Blowfish(key) + + msg = "TRUE{0}|{1}".format(len(plaintext), plaintext) + while len(msg) % 8 > 0: + msg += " " # pad message to form complete 8-byte blocks + + blocks = [msg[f:f+8] for f in range(0, len(msg), 8)] + cyphertext = ''.join(map(cypher.encrypt, blocks)) + + return cyphertext.encode('hex') + +def decrypt(key, cyphertext): + """Decrypt the result of encrypt() using the original key, or raise + IncorrectKeyError(). If the cyphertext is malformed, raise + BadCyphertextError().""" + cypher = Blowfish(key) + + try: + cyphertext = cyphertext.decode("hex") + except TypeError as e: + raise BadCyphertextError(e) + + if len(cyphertext) % 8 > 0: + raise BadCyphertextError("cyphertext cannot be broken into " + + "8-byte blocks evenly") + + blocks = [cyphertext[f:f+8] for f in range(0, len(cyphertext), 8)] + msg = ''.join(map(cypher.decrypt, blocks)) + + if not msg.startswith("TRUE"): # sanity check to ensure valid decryption + raise IncorrectKeyError() + + size, msg = msg[4:].split("|", 1) + while len(msg) > int(size): + msg = msg[:-1] # remove the padding that we applied earlier + + return msg if __name__ == '__main__': - key = 'This is a test key' - cipher = Blowfish (key) - - print "Testing encryption:" - xl = 123456 - xr = 654321 - print "\tPlain text: (%s, %s)" %(xl, xr) - cl, cr = cipher.cipher (xl, xr, cipher.ENCRYPT) - print "\tCrypted is: (%s, %s)" %(cl, cr) - dl, dr = cipher.cipher (cl, cr, cipher.DECRYPT) - print "\tUnencrypted is: (%s, %s)" %(dl, dr) - - print "Testing buffer encrypt:" - text = 'testtest' - print "\tText: %s" %text - crypted = cipher.encrypt (text) - print "\tEncrypted: %s" %crypted - decrypted = cipher.decrypt (crypted) - print "\tDecrypted: %s" %decrypted + action = raw_input("Would you like to [e]ncrypt or [d]ecrypt? ") + if action.lower().startswith("e"): + key = raw_input("Enter a key: ") + plaintext = raw_input("Enter a message to encrypt: ") + print "\n" + encrypt(key, plaintext) + elif action.lower().startswith("d"): + key = raw_input("Enter a key: ") + cyphertext = raw_input("Enter a message to decrypt: ") + print "\n" + decrypt(key, cyphertext) + else: + print "Unknown action: '{0}'.".format(op) From db0b125897d752f11b632e73fd66dd541fa39b98 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 18 Jun 2011 18:55:27 -0400 Subject: [PATCH 017/692] specify core/main.py as an absolute path, so we don't have to run 'python earwigbot.py' from within earwigbot/, but we can also do 'python /path/to/earwigbot.py' --- earwigbot.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/earwigbot.py b/earwigbot.py index b18f1bc..5543221 100644 --- a/earwigbot.py +++ b/earwigbot.py @@ -4,7 +4,7 @@ """ EarwigBot -A thin wrapper for EarwigBot's main bot code, located in core/main.py. This +A thin wrapper for EarwigBot's main bot code, specified by bot_script. This wrapper will automatically restart the bot when it shuts down (from !restart, for example). It requests the bot's password at startup and reuses it every time the bot restarts internally, so you do not need to re-enter the password @@ -16,6 +16,7 @@ markdown format!) and the LICENSE for licensing information. from getpass import getpass from subprocess import Popen, PIPE +from os import path from sys import executable from time import sleep @@ -27,6 +28,8 @@ __license__ = "MIT License" __version__ = "0.1dev" __email__ = "ben.kurtovic@verizon.net" +bot_script = path.join(path.dirname(path.abspath(__file__)), "core", "main.py") + def main(): print "EarwigBot v{0}\n".format(__version__) @@ -37,7 +40,7 @@ def main(): key = None while 1: - bot = Popen([executable, 'core/main.py'], stdin=PIPE) + bot = Popen([executable, bot_script], stdin=PIPE) bot.communicate(key) # give the key to core.config.load() return_code = bot.wait() if return_code == 1: From 8e5af3dff846e6a02b2c64ca5d9efdc8be63dd81 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 00:53:28 -0400 Subject: [PATCH 018/692] import lib.blowfish in core.config and decrypt passwords correctly; Exception -> Error in custom config exception names --- core/config.py | 48 +++++++++++++++++++++--------------------------- earwigbot.py | 2 +- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/core/config.py b/core/config.py index 2169481..df7c25f 100644 --- a/core/config.py +++ b/core/config.py @@ -16,6 +16,8 @@ from os import makedirs, path from xml.dom import minidom from xml.parsers.expat import ExpatError +from lib import blowfish + script_dir = path.dirname(path.abspath(__file__)) root_dir = path.split(script_dir)[0] config_path = path.join(root_dir, "config.xml") @@ -23,17 +25,17 @@ config_path = path.join(root_dir, "config.xml") _config = None # holds the parsed DOM object for our config file config = None # holds an instance of Container() with our config data -class ConfigParseException(Exception): +class ConfigParseError(Exception): """Base exception for when we could not parse the config file.""" -class TypeMismatchException(ConfigParseException): +class TypeMismatchError(ConfigParseError): """A field does not fit to its expected type; e.g., an arbitrary string where we expected a boolean or integer.""" -class MissingElementException(ConfigParseException): +class MissingElementError(ConfigParseError): """An element in the config file is missing a required sub-element.""" -class MissingAttributeException(ConfigParseException): +class MissingAttributeError(ConfigParseError): """An element is missing a required attribute to be parsed correctly.""" class Container(object): @@ -58,7 +60,7 @@ def verify_config(): else: if not _config.getElementsByTagName("config"): e = "Config file is missing a tag." - raise MissingElementException(e) + raise MissingElementError(e) return are_passwords_encrypted() else: print "You haven't configured the bot yet!" @@ -81,18 +83,6 @@ def make_new_config(): return is_encrypted -def encrypt_password(password, key): - """If passwords are supposed to be encrypted, use this function to do that - using a user-provided key.""" - # TODO: stub - return password - -def decrypt_password(password, key): - """If passwords are encrypted, use this function to decrypt them using a - user-provided key.""" - # TODO: stub - return password - def are_passwords_encrypted(): """Determine if the passwords in our config file are encrypted, returning either True or False.""" @@ -102,8 +92,8 @@ def are_passwords_encrypted(): def attribute_to_bool(element, attribute, default=None): """Return True if the value of element's attribute is 'true', '1', or 'on'; return False if it is 'false', '0', or 'off' (regardless of - capitalization); return default if it is empty; raise TypeMismatchException - if it does match any of those.""" + capitalization); return default if it is empty; raise TypeMismatchError if + it does match any of those.""" value = element.getAttribute(attribute).lower() if value in ["true", "1", "on"]: return True @@ -114,7 +104,7 @@ def attribute_to_bool(element, attribute, default=None): else: e = ("Expected a bool in attribute '{0}' of element '{1}', but " + "got '{2}'.").format(attribute, element.tagName, value) - raise TypeMismatchException(e) + raise TypeMismatchError(e) def get_first_element(parent, tag_name): """Return the first child of the parent element with the given tag name, or @@ -126,22 +116,22 @@ def get_first_element(parent, tag_name): def get_required_element(parent, tag_name): """Return the first child of the parent element with the given tag name, or - raise MissingElementException() if no child of that name exists.""" + raise MissingElementError() if no child of that name exists.""" element = get_first_element(parent, tag_name) if not element: e = "A <{0}> tag is missing a required <{1}> child tag.".format( parent.tagName, tag_name) - raise MissingElementException(e) + raise MissingElementError(e) return element def get_required_attribute(element, attr_name): """Return the value of the attribute 'attr_name' in 'element'. If - undefined, raise MissingAttributeException().""" + undefined, raise MissingAttributeError().""" attribute = element.getAttribute(attr_name) if not attribute: e = "A <{0}> tag is missing the required attribute '{1}'.".format( element.tagName, attr_name) - raise MissingAttributeException(e) + raise MissingAttributeError(e) return attribute def parse_config(key): @@ -149,9 +139,13 @@ def parse_config(key): parsing exceptions and report them to the user cleanly.""" try: _parse_config(key) - except ConfigParseException as e: + except ConfigParseError as error: print "\nError parsing config file:" - print e + print error + exit(1) + except blowfish.BlowfishError as error: + print "\nError decrypting passwords:" + print error exit(1) def _parse_config(key): @@ -207,7 +201,7 @@ def parse_irc_server(data, key): server.nickserv.username = get_required_attribute(nickserv, "username") password = get_required_attribute(nickserv, "password") if are_passwords_encrypted(): - server.nickserv.password = decrypt_password(password, key) + server.nickserv.password = blowfish.decrypt(key, password) else: server.nickserv.password = password diff --git a/earwigbot.py b/earwigbot.py index 5543221..3542076 100644 --- a/earwigbot.py +++ b/earwigbot.py @@ -41,7 +41,7 @@ def main(): while 1: bot = Popen([executable, bot_script], stdin=PIPE) - bot.communicate(key) # give the key to core.config.load() + bot.communicate(key) # give the key to core.config.load_config() return_code = bot.wait() if return_code == 1: exit() # let critical exceptions in the subprocess cause us to From 2c7b684fa074f1af92d29692b55ace433f21eec2 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 01:40:22 -0400 Subject: [PATCH 019/692] simplify exceptions into four classes instead of eight; make error messages more verbose --- lib/blowfish.py | 54 ++++++++++++++++++++---------------------------------- 1 file changed, 20 insertions(+), 34 deletions(-) diff --git a/lib/blowfish.py b/lib/blowfish.py index 8a5e5f2..25a1908 100644 --- a/lib/blowfish.py +++ b/lib/blowfish.py @@ -33,16 +33,6 @@ The entire Blowfish() class (excluding verify_key()) is by Michael Gilfix Blowfish.verify_key(), exception classes, encrypt() and decrypt() wrappers, and interactive mode are by Ben Kurtovic . - -Map of exceptions: - * BlowfishError - * BlockSizeError - * KeyLengthError - * KeyTooShortError - * KeyTooLongError - * DecryptionError - * IncorrectKeyError - * BadCyphertextError """ class BlowfishError(Exception): @@ -53,22 +43,12 @@ class BlockSizeError(BlowfishError): """Attempted to handle a block not 8 bytes in length.""" class KeyLengthError(BlowfishError): - """Base class for invalid key length exceptions.""" - -class KeyTooShortError(KeyLengthError): - """The given key is too short: it is less than 8 bytes (64 bits).""" - -class KeyTooLongError(KeyLengthError): - """The given key is too long: it is more than 56 bytes (448 bits.""" + """Attempted to use a key that is either less than 8 bytes or more than 56 + bytes in length.""" class DecryptionError(BlowfishError): - """Base class for exceptions that occur during decryption only.""" - -class IncorrectKeyError(DecryptionError): - """Attempted to decrypt something with the wrong key.""" - -class BadCyphertextError(DecryptionError): - """The given cyphertext is malformed and cannot be decrypted.""" + """Attempted to decrypt malformed cyphertext (e.g., not evenly divisible + into 8-byte blocks) or attempted to decrypt using a bad key.""" class Blowfish(object): """Blowfish encryption Scheme @@ -462,7 +442,8 @@ class Blowfish(object): def encrypt(self, data): if not len(data) == 8: - raise BlockSizeError("{0} != 8".format(len(data))) + raise BlockSizeError("blocks must be 8 bytes long, but tried to " + + "encrypt one {0} bytes long".format(len(data))) # Use big endianess since that's what everyone else uses xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) @@ -477,7 +458,8 @@ class Blowfish(object): def decrypt(self, data): if not len(data) == 8: - raise BlockSizeError("{0} != 8".format(len(data))) + raise BlockSizeError("blocks must be 8 bytes long, but tried to " + + "decrypt one {0} bytes long".format(len(data))) # Use big endianess since that's what everyone else uses cl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24) @@ -503,11 +485,13 @@ class Blowfish(object): """Make sure our key is not too short or too long; if there's a problem, raise KeyTooShortError() or KeyTooLongError().""" if not key: - raise KeyTooShortError("no key given") + raise KeyLengthError("no key given") if len(key) < 8: - raise KeyTooShortError("{0} < 8".format(len(key))) + raise KeyLengthError(("key is {0} bytes long, but it must be at " + + "least 8").format(len(key))) if len(key) > 56: - raise KeyTooLongError("{0} > 56".format(len(key))) + raise KeyLengthError(("key is {0} bytes long, but it must be " + + "less than 56").format(len(key))) def encrypt(key, plaintext): """Encrypt any length of plaintext using a given key that must be between @@ -534,18 +518,20 @@ def decrypt(key, cyphertext): try: cyphertext = cyphertext.decode("hex") - except TypeError as e: - raise BadCyphertextError(e) + except TypeError as error: + e = error.message + raise DecryptionError("cyphertext could not be decoded: " + e.lower()) if len(cyphertext) % 8 > 0: - raise BadCyphertextError("cyphertext cannot be broken into " + - "8-byte blocks evenly") + raise DecryptionError("cyphertext cannot be broken into " + + "8-byte blocks evenly") blocks = [cyphertext[f:f+8] for f in range(0, len(cyphertext), 8)] msg = ''.join(map(cypher.decrypt, blocks)) if not msg.startswith("TRUE"): # sanity check to ensure valid decryption - raise IncorrectKeyError() + raise DecryptionError("the given key is incorrect, or part of the " + + "cyphertext is malformed") size, msg = msg[4:].split("|", 1) while len(msg) > int(size): From 814c9efdce7c9230f4bd97a72f4fa6c314b81d60 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 01:52:21 -0400 Subject: [PATCH 020/692] nicer error message that actually tells us what's going on, thanks to the changes in lib.blowfish upstream (on develop) --- core/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/config.py b/core/config.py index df7c25f..3607502 100644 --- a/core/config.py +++ b/core/config.py @@ -145,7 +145,7 @@ def parse_config(key): exit(1) except blowfish.BlowfishError as error: print "\nError decrypting passwords:" - print error + print "{0}: {1}.".format(error.__class__.__name__, error) exit(1) def _parse_config(key): From 848ac58e7a6740e60a136e93dd2da71b8a5daf0d Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 02:06:37 -0400 Subject: [PATCH 021/692] dramatically simplify error handling with !encrypt/!decrypt irc commands, thanks to previous commit --- irc/commands/crypt.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/irc/commands/crypt.py b/irc/commands/crypt.py index 92793d3..7b167d2 100644 --- a/irc/commands/crypt.py +++ b/irc/commands/crypt.py @@ -63,16 +63,9 @@ class Cryptography(BaseCommand): try: if data.command == "encrypt": - result = blowfish.encrypt(key, text) + self.connection.reply(data, blowfish.encrypt(key, text)) else: - result = blowfish.decrypt(key, text) - except blowfish.KeyTooShortError: - self.connection.reply(data, "key is too short.") - except blowfish.KeyTooLongError: - self.connection.reply(data, "key is too long.") - except blowfish.IncorrectKeyError: - self.connection.reply(data, "key is incorrect!") - except blowfish.BadCyphertextError as e: - self.connection.reply(data, "bad cyphertext: {0}.".format(e)) - else: - self.connection.reply(data, result) + self.connection.reply(data, blowfish.decrypt(key, text)) + except blowfish.BlowfishError as error: + self.connection.reply(data, "{0}: {1}.".format( + error.__class__.__name__, error)) From 430ba061af892dc6da52a03ea57594b0683c6332 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 23:22:01 -0400 Subject: [PATCH 022/692] store config differently (in five separate global variables instead of one) to make accessing it cleaner; convert core/main.py to new config system as well as irc/frontend.py -- both seem to be working --- core/config.py | 95 ++++++++++++++++++++++++++++++++++++--------------------- core/main.py | 12 ++++---- irc/frontend.py | 71 ++++++++++++++++++++++++++++-------------- 3 files changed, 114 insertions(+), 64 deletions(-) diff --git a/core/config.py b/core/config.py index 3607502..486367a 100644 --- a/core/config.py +++ b/core/config.py @@ -7,8 +7,14 @@ This handles all tasks involving reading and writing to our config file, including encrypting and decrypting passwords and making a new config file from scratch at the inital bot run. -Usually you'll just want to do "from core.config import config" and access -config data from within that object. +Usually you'll just want to do "from core import config" and access config data +from within config's five global variables: + +* config.components +* config.wiki +* config.irc +* config.schedule +* config.watcher """ from collections import defaultdict @@ -23,7 +29,9 @@ root_dir = path.split(script_dir)[0] config_path = path.join(root_dir, "config.xml") _config = None # holds the parsed DOM object for our config file -config = None # holds an instance of Container() with our config data + +# initialize our five global variables to store config data +components, wiki, irc, schedule, watcher = (None, None, None, None, None) class ConfigParseError(Exception): """Base exception for when we could not parse the config file.""" @@ -84,27 +92,14 @@ def make_new_config(): return is_encrypted def are_passwords_encrypted(): - """Determine if the passwords in our config file are encrypted, returning - either True or False.""" + """Determine if the passwords in our config file are encrypted; return + either True or False, or raise an exception if there was a problem reading + the config file.""" element = _config.getElementsByTagName("config")[0] - return attribute_to_bool(element, "encrypt-passwords", default=False) - -def attribute_to_bool(element, attribute, default=None): - """Return True if the value of element's attribute is 'true', '1', or 'on'; - return False if it is 'false', '0', or 'off' (regardless of - capitalization); return default if it is empty; raise TypeMismatchError if - it does match any of those.""" - value = element.getAttribute(attribute).lower() - if value in ["true", "1", "on"]: - return True - elif value in ["false", "0", "off"]: + attribute = element.getAttribute("encrypt-passwords") + if not attribute: return False - elif value == '': - return default - else: - e = ("Expected a bool in attribute '{0}' of element '{1}', but " + - "got '{2}'.").format(attribute, element.tagName, value) - raise TypeMismatchError(e) + return attribute_to_bool(attribute, element, "encrypt-passwords") def get_first_element(parent, tag_name): """Return the first child of the parent element with the given tag name, or @@ -134,6 +129,32 @@ def get_required_attribute(element, attr_name): raise MissingAttributeError(e) return attribute +def attribute_to_bool(value, element, attr_name): + """Return True if 'value' is 'true', '1', or 'on', return False if it is + 'false', '0', or 'off' (regardless of capitalization), or raise + TypeMismatchError() if it does match any of those. 'element' and + 'attr_name' are only used to generate the error message.""" + lcase = value.lower() + if lcase in ["true", "1", "on"]: + return True + elif lcase in ["false", "0", "off"]: + return False + else: + e = ("Expected a bool in attribute '{0}' of tag '{1}', but got '{2}'." + ).format(attr_name, element.tagName, value) + raise TypeMismatchError(e) + +def attribute_to_int(value, element, attr_name): + """Return 'value' after it is converted to an integer. If it could not be + converted, raise TypeMismatchError() using 'element' and 'attr_name' only + to give the user information about what happened.""" + try: + return int(value) + except ValueError: + e = ("Expected an integer in attribute '{0}' of tag '{1}', but got " + + "'{2}'.").format(attr_name, element.tagName, value) + raise TypeMismatchError(e) + def parse_config(key): """A thin wrapper for the actual config parser in _parse_config(): catch parsing exceptions and report them to the user cleanly.""" @@ -149,21 +170,20 @@ def parse_config(key): exit(1) def _parse_config(key): - """Parse config data from a DOM object into the 'config' global variable. - The key is used to unencrypt passwords stored in the XML config file.""" + """Parse config data from a DOM object into the five global variables that + store our config info. The key is used to unencrypt passwords stored in the + XML config file.""" + global components, wiki, irc, schedule, watcher + _load_config() # we might be re-loading unnecessarily here, but no harm in # that! data = _config.getElementsByTagName("config")[0] - cfg = Container() - cfg.components = parse_components(data) - cfg.wiki = parse_wiki(data, key) - cfg.irc = parse_irc(data, key) - cfg.schedule = parse_schedule(data) - cfg.watcher = parse_watcher(data) - - global config - config = cfg + components = parse_components(data) + wiki = parse_wiki(data, key) + irc = parse_irc(data, key) + schedule = parse_schedule(data) + watcher = parse_watcher(data) def parse_components(data): """Parse everything within the XML tag of our config file. @@ -187,14 +207,17 @@ def parse_wiki(data, key): def parse_irc_server(data, key): """Parse everything within a tag.""" server = Container() - connection = get_required_element(data, "connection") + server.host = get_required_attribute(connection, "host") server.port = get_required_attribute(connection, "port") server.nick = get_required_attribute(connection, "nick") server.ident = get_required_attribute(connection, "ident") server.realname = get_required_attribute(connection, "realname") + # convert the port from a string to an int + server.port = attribute_to_int(server.port, connection, "port") + nickserv = get_first_element(data, "nickserv") if nickserv: server.nickserv = Container() @@ -204,10 +227,12 @@ def parse_irc_server(data, key): server.nickserv.password = blowfish.decrypt(key, password) else: server.nickserv.password = password + else: + server.nickserv = None + server.channels = list() channels = get_first_element(data, "channels") if channels: - server.channels = list() for channel in channels.getElementsByTagName("channel"): name = get_required_attribute(channel, "name") server.channels.append(name) diff --git a/core/main.py b/core/main.py index 9f0cc7f..31d6149 100644 --- a/core/main.py +++ b/core/main.py @@ -42,7 +42,7 @@ root_dir = os.path.split(script_dir)[0] # the bot's "root" directory relative sys.path.append(root_dir) # make sure we look in the root dir for modules from core import config -#from irc import frontend, watcher +from irc import frontend#, watcher #from wiki import task_manager f_conn = None @@ -87,7 +87,7 @@ def irc_frontend(components): f_conn = frontend.get_connection() frontend.startup(f_conn) - if enable_wiki_schedule: + if config.components["wiki_schedule"]: print "\nStarting wiki scheduler..." task_manager.load_tasks() t_scheduler = threading.Thread(target=wiki_scheduler) @@ -95,7 +95,7 @@ def irc_frontend(components): t_scheduler.daemon = True t_scheduler.start() - if enable_irc_watcher: + if config.components["irc_watcher"]: print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) t_watcher.name = "irc-watcher" @@ -104,7 +104,7 @@ def irc_frontend(components): frontend.main() - if enable_irc_watcher: + if config.components["irc_watcher"]: w_conn.close() f_conn.close() @@ -115,7 +115,7 @@ def run(): key = None config.parse_config(key) # load data from the config file and parse it # using the unlock key - components = config.config.components + components = config.components if components["irc_frontend"]: # make the frontend run on our primary irc_frontend(components) # thread if enabled, and enable additional @@ -124,7 +124,7 @@ def run(): elif components["wiki_schedule"]: # run the scheduler on the main print "Starting wiki scheduler..." # thread, but also run the IRC task_manager.load_tasks() # watcher on another thread iff it - if enable_irc_watcher: # is enabled + if components["irc_watcher"]: # is enabled print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) t_watcher.name = "irc-watcher" diff --git a/irc/frontend.py b/irc/frontend.py index 293bc0a..d8d4991 100644 --- a/irc/frontend.py +++ b/irc/frontend.py @@ -1,11 +1,17 @@ # -*- coding: utf-8 -*- -## Imports -import re, time +""" +EarwigBot's Front-end IRC Component -from config.irc import * -from config.secure import * +The IRC frontend runs on a normal IRC server and expects users to interact with +it and give it commands. Commands are stored as "command classes", subclasses +of BaseCommand in irc/base_command.py. All command classes are automatically +imported by irc/command_handler.py if they are in irc/commands. +""" +from re import findall + +from core import config from irc import command_handler from irc.connection import * from irc.data import Data @@ -13,16 +19,24 @@ from irc.data import Data connection = None def get_connection(): - connection = Connection(HOST, PORT, NICK, IDENT, REALNAME) + """Return a new Connection() instance with information about our server + connection, but don't actually connect yet.""" + cf = config.irc.frontend + connection = Connection(cf.host, cf.port, cf.nick, cf.nick, cf.realname) return connection def startup(conn): + """Accept a single arg, a Connection() object, and set our global variable + 'connection' to it. Load all command classes in irc/commands with + command_handler, and then establish a connection with the IRC server.""" global connection connection = conn command_handler.load_commands(connection) connection.connect() def main(): + """Main loop for the Frontend IRC Bot component. get_connection() and + startup() should have already been called.""" read_buffer = str() while 1: @@ -35,41 +49,52 @@ def main(): lines = read_buffer.split("\n") read_buffer = lines.pop() - for line in lines: + for line in lines: # handle a single message from IRC line = line.strip().split() - data = Data() + data = Data() # new Data() instance to store info about this line data.line = line if line[1] == "JOIN": - data.nick, data.ident, data.host = re.findall(":(.*?)!(.*?)@(.*?)\Z", line[0])[0] + data.nick, data.ident, data.host = findall( + ":(.*?)!(.*?)@(.*?)\Z", line[0])[0] data.chan = line[2][1:] - - command_handler.check("join", data) # check if there's anything we can respond to, and if so, respond + command_handler.check("join", data) # check for 'join' hooks in + # our commands if line[1] == "PRIVMSG": - data.nick, data.ident, data.host = re.findall(":(.*?)!(.*?)@(.*?)\Z", line[0])[0] + data.nick, data.ident, data.host = findall( + ":(.*?)!(.*?)@(.*?)\Z", line[0])[0] data.msg = ' '.join(line[3:])[1:] data.chan = line[2] - if data.chan == NICK: # this is a privmsg to us, so set 'chan' as the nick of the sender + if data.chan == config.irc.frontend.nick: + # this is a privmsg to us, so set 'chan' as the nick of the + # sender, then check for private-only command hooks data.chan = data.nick - command_handler.check("msg_private", data) # only respond if it's a private message + command_handler.check("msg_private", data) else: - command_handler.check("msg_public", data) # only respond if it's a public (channel) message + # check for public-only command hooks + command_handler.check("msg_public", data) - command_handler.check("msg", data) # check for general messages + # check for command hooks that apply to all messages + command_handler.check("msg", data) - if data.msg.startswith("!restart"): # hardcode the !restart command (we can't restart from within an ordinary command) - if data.host in OWNERS: + # hardcode the !restart command (we can't restart from within + # an ordinary command) + if data.msg in ["!restart", ".restart"]: + if data.host in config.irc.permissions["owners"]: print "Restarting bot per owner request..." return - if line[0] == "PING": # If we are pinged, pong back to the server + if line[0] == "PING": # if we are pinged, pong back to the server connection.send("PONG %s" % line[1]) - if line[1] == "376": - if NS_AUTH: # if we're supposed to auth to nickserv, do that - connection.say("NickServ", "IDENTIFY %s %s" % (NS_USER, NS_PASS)) - time.sleep(3) # sleep for a bit so we don't join channels un-authed - for chan in CHANS: # join all of our startup channels + if line[1] == "376": # we've successfully connected to the network + ns = config.irc.frontend.nickserv + if ns: # if we're supposed to auth to nickserv, do that + connection.say("NickServ", "IDENTIFY %s %s" % (ns.username, + ns.password)) + + # join all of our startup channels + for chan in config.irc.frontend.channels: connection.join(chan) From e21a4dfb76b8dbf7f769f0d763d9142ac3da3493 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 19 Jun 2011 23:56:54 -0400 Subject: [PATCH 023/692] converting four IRC command classes to use new config system; everything's been converted except for irc/watcher.py and everything in wiki/ --- irc/commands/afc_status.py | 3 +-- irc/commands/chanops.py | 4 ++-- irc/commands/git.py | 4 ++-- irc/commands/tasks.py | 12 ++++++------ 4 files changed, 11 insertions(+), 12 deletions(-) diff --git a/irc/commands/afc_status.py b/irc/commands/afc_status.py index 4b3553a..dd0248c 100644 --- a/irc/commands/afc_status.py +++ b/irc/commands/afc_status.py @@ -6,7 +6,6 @@ import json import re import urllib -from config.watcher import * from irc.base_command import BaseCommand class AFCStatus(BaseCommand): @@ -22,7 +21,7 @@ class AFCStatus(BaseCommand): data.command == "number" or data.command == "afc_status"): return True try: - if data.line[1] == "JOIN" and data.chan in AFC_CHANS: + if data.line[1] == "JOIN" and data.chan == "#wikipedia-en-afc": return True except IndexError: pass diff --git a/irc/commands/chanops.py b/irc/commands/chanops.py index e7b4683..a2a9cc6 100644 --- a/irc/commands/chanops.py +++ b/irc/commands/chanops.py @@ -3,7 +3,7 @@ # Voice/devoice/op/deop users in the channel. from irc.base_command import BaseCommand -from config.irc import * +from core import config class ChanOps(BaseCommand): def get_hooks(self): @@ -19,7 +19,7 @@ class ChanOps(BaseCommand): return False def process(self, data): - if data.host not in ADMINS: + if data.host not in config.irc.permissions["admins"]: self.connection.reply(data, "you must be a bot admin to use this command.") return diff --git a/irc/commands/git.py b/irc/commands/git.py index 7b76cf8..a919904 100644 --- a/irc/commands/git.py +++ b/irc/commands/git.py @@ -4,8 +4,8 @@ import shlex, subprocess, re -from config.irc import * from irc.base_command import BaseCommand +from core import config class Git(BaseCommand): def get_hooks(self): @@ -21,7 +21,7 @@ class Git(BaseCommand): def process(self, data): self.data = data - if data.host not in OWNERS: + if data.host not in config.irc.permissions["owners"]: self.connection.reply(data, "you must be a bot owner to use this command.") return diff --git a/irc/commands/tasks.py b/irc/commands/tasks.py index d1903bc..58050d0 100644 --- a/irc/commands/tasks.py +++ b/irc/commands/tasks.py @@ -2,13 +2,13 @@ # Manage wiki tasks from IRC, and check on thread status. -import threading, re +import threading +import re from irc.base_command import BaseCommand from irc.data import * from wiki import task_manager -from config.main import * -from config.irc import * +from core import config class Tasks(BaseCommand): def get_hooks(self): @@ -24,7 +24,7 @@ class Tasks(BaseCommand): def process(self, data): self.data = data - if data.host not in OWNERS: + if data.host not in config.irc.permissions["owners"]: self.connection.reply(data, "at this time, you must be a bot owner to use this command.") return @@ -116,9 +116,9 @@ class Tasks(BaseCommand): def get_main_thread_name(self): """Return the "proper" name of the MainThread; e.g. "irc-frontend" or "irc-watcher".""" - if enable_irc_frontend: + if config.components["irc_frontend"]: return "irc-frontend" - elif enable_wiki_schedule: + elif config.components["wiki_schedule"]: return "wiki-scheduler" else: return "irc-watcher" From d57f2623d23009bdedfce441abed6266fdf8f095 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Wed, 22 Jun 2011 20:11:29 -0400 Subject: [PATCH 024/692] parse remaining parts of config.xml; getting rid of config.watcher and moving to irc/watcher_logic.py; convert irc/watcher.py and wiki/task_manager.py to new config system; other changes/fixes/whatever --- core/config.py | 53 +++++++++++++++++++++++++++++-------- core/main.py | 6 ++--- irc/frontend.py | 2 +- irc/watcher.py | 66 ++++++++++++++++++++++++++++++---------------- irc/watcher_logic.py | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++ wiki/task_manager.py | 70 ++++++++++++++++++++++++++++++------------------- 6 files changed, 206 insertions(+), 65 deletions(-) create mode 100644 irc/watcher_logic.py diff --git a/core/config.py b/core/config.py index 486367a..b1331ce 100644 --- a/core/config.py +++ b/core/config.py @@ -8,13 +8,12 @@ including encrypting and decrypting passwords and making a new config file from scratch at the inital bot run. Usually you'll just want to do "from core import config" and access config data -from within config's five global variables: +from within config's four global variables: * config.components * config.wiki * config.irc * config.schedule -* config.watcher """ from collections import defaultdict @@ -170,10 +169,10 @@ def parse_config(key): exit(1) def _parse_config(key): - """Parse config data from a DOM object into the five global variables that + """Parse config data from a DOM object into the four global variables that store our config info. The key is used to unencrypt passwords stored in the XML config file.""" - global components, wiki, irc, schedule, watcher + global components, wiki, irc, schedule _load_config() # we might be re-loading unnecessarily here, but no harm in # that! @@ -183,7 +182,6 @@ def _parse_config(key): wiki = parse_wiki(data, key) irc = parse_irc(data, key) schedule = parse_schedule(data) - watcher = parse_watcher(data) def parse_components(data): """Parse everything within the XML tag of our config file. @@ -270,11 +268,44 @@ def parse_irc(data, key): irc.permissions[group_name].append(hostname) return irc - + def parse_schedule(data): - """Parse everything within the tag of our XML config file.""" - pass + """Store the element in schedule.data and the _schedule() + function as schedule.check().""" + schedule = Container() + schedule.check = _schedule + schedule.data = get_first_element(data, "schedule") + return schedule -def parse_watcher(data): - """Parse everything within the tag of our XML config file.""" - pass +def _schedule(minute, hour, month_day, month, week_day): + """Return a list of tasks that are scheduled to run at the time specified + by the function args. The schedule data comes from our config file's + tag, which is stored as schedule.data. Call this function with + config.schedule.check(args).""" + tasks = [] # tasks to run this turn, each as a tuple of (task_name, + # kwargs), or just task_name + + now = {"minute": minute, "hour": hour, "month_day": month_day, + "month": month, "week_day": week_day} + + for when in schedule.data.getElementsByTagName("when"): + do = True + for key, value in now.items(): + if when.hasAttribute(key): + req = when.getAttribute(key) + if attribute_to_int(req, when, key) != value: + do = False + break + if do: + for task in when.getElementsByTagName("task"): + name = get_required_attribute(task, "name") + args = dict() + for key in task.attributes.keys(): + args[key] = task.getAttribute(key) + del args["name"] + if args: + tasks.append((name, args)) + else: + tasks.append(name) + + return tasks diff --git a/core/main.py b/core/main.py index 31d6149..649e1f6 100644 --- a/core/main.py +++ b/core/main.py @@ -42,8 +42,8 @@ root_dir = os.path.split(script_dir)[0] # the bot's "root" directory relative sys.path.append(root_dir) # make sure we look in the root dir for modules from core import config -from irc import frontend#, watcher -#from wiki import task_manager +from irc import frontend, watcher +from wiki import task_manager f_conn = None w_conn = None @@ -126,7 +126,7 @@ def run(): task_manager.load_tasks() # watcher on another thread iff it if components["irc_watcher"]: # is enabled print "\nStarting IRC watcher..." - t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) + t_watcher = threading.Thread(target=irc_watcher, args=()) t_watcher.name = "irc-watcher" t_watcher.daemon = True t_watcher.start() diff --git a/irc/frontend.py b/irc/frontend.py index d8d4991..38d326a 100644 --- a/irc/frontend.py +++ b/irc/frontend.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """ -EarwigBot's Front-end IRC Component +EarwigBot's IRC Front-end Component The IRC frontend runs on a normal IRC server and expects users to interact with it and give it commands. Commands are stored as "command classes", subclasses diff --git a/irc/watcher.py b/irc/watcher.py index 2aff8dd..bbc17c9 100644 --- a/irc/watcher.py +++ b/irc/watcher.py @@ -1,20 +1,34 @@ # -*- coding: utf-8 -*- -## Imports -from config.irc import * -from config.main import * -from config.watcher import * +""" +EarwigBot's IRC Watcher Component +The IRC watcher runs on a wiki recent-changes server and listens for edits. +Users cannot interact with this part of the bot. When an event occurs, run it +through irc/watcher_logic.py's process() function, which can result in either +wiki bot tasks being started (listed in wiki/tasks/) or messages being sent to +channels in the IRC frontend. +""" + +from core import config from irc.connection import * from irc.rc import RC +from irc import watcher_logic -global frontend_conn +frontend_conn = None def get_connection(): - connection = Connection(WATCHER_HOST, WATCHER_PORT, NICK, IDENT, REALNAME) + """Return a new Connection() instance with information about our server + connection, but don't actually connect yet.""" + cf = config.irc.watcher + connection = Connection(cf.host, cf.port, cf.nick, cf.nick, cf.realname) return connection -def main(connection, f_conn): +def main(connection, f_conn=None): + """Main loop for the Watcher IRC Bot component. get_connection() should + have already been called and the connection should have been started with + connection.connect(). Accept the frontend connection as well as an optional + parameter in order to send messages directly to frontend IRC channels.""" global frontend_conn frontend_conn = f_conn read_buffer = str() @@ -33,26 +47,32 @@ def main(connection, f_conn): if line[1] == "PRIVMSG": chan = line[2] - if chan != WATCHER_CHAN: # if we're getting a msg from another channel, ignore it + + # ignore messages originating from channels not in our list, to + # prevent someone PMing us false data + if chan not in config.irc.watcher.channels: continue msg = ' '.join(line[3:])[1:] - rc = RC(msg) # create a new RC object to store this change's data - rc.parse() - check(rc) + rc = RC(msg) # new RC object to store this event's data + rc.parse() # parse a message into pagenames, usernames, etc. + process(rc) # report to frontend channels or start tasks - if line[0] == "PING": # If we are pinged, pong back to the server + if line[0] == "PING": # if we are pinged, pong back to the server connection.send("PONG %s" % line[1]) - if line[1] == "376": # Join the recent changes channel when we've finished starting up - connection.join(WATCHER_CHAN) - -def check(rc): - """check if we're supposed to report this message anywhere""" - results = process(rc) # process the message in config/watcher.py, and get a list of channels to send it to - if not results: - return - pretty = rc.get_pretty() - if enable_irc_frontend: - for chan in results: + # when we've finished starting up, join all watcher channels + if line[1] == "376": + for chan in config.irc.watcher.channels: + connection.join(chan) + +def process(rc): + """Process a message from IRC (technically, an RC object). The actual + processing is configurable, so we don't have that hard-coded here. We + simply call irc/watcher_logic.py's process() function and expect a list of + channels back, which we report the event data to.""" + chans = watcher_logic.process(rc) + if chans and frontend_conn: + pretty = rc.get_pretty() + for chan in chans: frontend_conn.say(chan, pretty) diff --git a/irc/watcher_logic.py b/irc/watcher_logic.py new file mode 100644 index 0000000..bcce171 --- /dev/null +++ b/irc/watcher_logic.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +""" +EarwigBot's IRC Watcher Logic + +This file contains (configurable!) rules that EarwigBot's watcher uses after it +recieves an event from IRC. + +This should, ideally, be in config.xml somehow, but Python code makes more +sense for this sort of thing... so... +""" + +import re + +from wiki import task_manager as tasks + +afc_prefix = "wikipedia( talk)?:(wikiproject )?articles for creation" + +# compile some regexps used when finding specific events +r_page = re.compile(afc_prefix) +r_ffu = re.compile("wikipedia( talk)?:files for upload") +r_move1 = re.compile("moved \[\[{}".format(afc_prefix)) +r_move2 = re.compile("moved \[\[(.*?)\]\] to \[\[{}".format(afc_prefix)) +r_moved_pages = re.compile("^moved \[\[(.*?)\]\] to \[\[(.*?)\]\]") +r_delete = re.compile("deleted \"\[\[{}".format(afc_prefix)) +r_deleted_page = re.compile("^deleted \"\[\[(.*?)\]\]") +r_restore = re.compile("restored \"\[\[{}".format(afc_prefix)) +r_restored_page = re.compile("^restored \"\[\[(.*?)\]\]") +r_protect = re.compile("protected \"\[\[{}".format(afc_prefix)) + +def process(rc): + """Given an RC() object, return a list of channels to report this event to. + Also, start any wiki bot tasks within this function if necessary.""" + chans = set() # channels to report this message to + page_name = rc.page.lower() + comment = rc.comment.lower() + + if "!earwigbot" in rc.msg.lower(): + chans.update(("##earwigbot", "#wikipedia-en-afc")) + + if r_page.search(page_name): + tasks.start_task("afc_statistics", action="process_edit", page=rc.page) + tasks.start_task("afc_copyvios", action="process_edit", page=rc.page) + chans.add("#wikipedia-en-afc") + + elif r_ffu.match(page_name): + chans.add("#wikipedia-en-afc") + + elif page_name.startswith("template:afc submission"): + chans.add("#wikipedia-en-afc") + + elif rc.flags == "move" and (r_move1.match(comment) or + r_move2.match(comment)): + p = r_moved_pages.findall(rc.comment)[0] + tasks.start_task("afc_statistics", action="process_move", pages=p) + tasks.start_task("afc_copyvios", action="process_move", pages=p) + chans.add("#wikipedia-en-afc") + + elif rc.flags == "delete" and r_delete.match(comment): + p = r_deleted_page.findall(rc.comment)[0][0] + tasks.start_task("afc_statistics", action="process_delete", page=p) + tasks.start_task("afc_copyvios", action="process_delete", page=p) + chans.add("#wikipedia-en-afc") + + elif rc.flags == "restore" and r_restore.match(comment): + p = r_restored_page.findall(rc.comment)[0][0] + tasks.start_task("afc_statistics", action="process_restore", page=p) + tasks.start_task("afc_copyvios", action="process_restore", page=p) + chans.add("#wikipedia-en-afc") + + elif rc.flags == "protect" and r_protect.match(comment): + chans.add("#wikipedia-en-afc") + + return chans diff --git a/wiki/task_manager.py b/wiki/task_manager.py index b17cbbb..3c37a63 100644 --- a/wiki/task_manager.py +++ b/wiki/task_manager.py @@ -1,25 +1,32 @@ # -*- coding: utf-8 -*- -# A module to manage bot tasks. +""" +EarwigBot's Wiki Bot Task Manager + +This module provides some functions to run and load bot tasks from wiki/tasks/. +""" import time import traceback import threading import os -from config import schedule +from core import config -task_list = dict() # the key is the task's name, the value is the task's class instance +# store loaded tasks as a dict where the key is the task name and the value is +# an instance of the task class (wiki.tasks.task_file.Task()) +task_list = dict() def load_tasks(): - """Load all valid task classes from wiki/tasks/, and add them to the task_list.""" - files = os.listdir(os.path.join("wiki", "tasks")) # get all files in wiki/tasks/ - files.sort() # alphabetically sort list of files + """Load all valid task classes from wiki/tasks/, and add them to the + task_list variable.""" + files = os.listdir(os.path.join("wiki", "tasks")) + files.sort() # alphabetically sort all files in wiki/tasks/ for f in files: - if not os.path.isfile(os.path.join("wiki", "tasks", f)): # ignore non-files - continue - if f.startswith("_") or not f.endswith(".py"): # ignore non-python files or files beginning with "_" - continue + if not os.path.isfile(os.path.join("wiki", "tasks", f)): + continue # ignore non-files + if f.startswith("_") or not f.endswith(".py"): + continue # ignore non-python files or files beginning with an _ load_class_from_file(f) print "Found %s tasks: %s." % (len(task_list), ', '.join(task_list.keys())) @@ -27,10 +34,10 @@ def load_class_from_file(f): """Look in a given file for the task class.""" global task_list - module = f[:-3] # strip .py from end + module = f[:-3] # strip .py from end try: exec "from wiki.tasks import %s as m" % module - except: # importing the file failed for some reason... + except: # importing the file failed for some reason... print "Couldn't load task file %s:" % f traceback.print_exc() return @@ -46,26 +53,34 @@ def load_class_from_file(f): def start_tasks(now=time.gmtime()): """Start all tasks that are supposed to be run at a given time.""" - tasks = schedule.check(now.tm_min, now.tm_hour, now.tm_mday, now.tm_mon, now.tm_wday) # get list of tasks to run this turn + tasks = config.schedule.check(now.tm_min, now.tm_hour, now.tm_mday, + now.tm_mon, now.tm_wday) # get list of tasks to run this turn + for task in tasks: - if isinstance(task, tuple): # they've specified kwargs, so pass those to start_task - start_task(task[0], **task[1]) - else: # otherwise, just pass task_name + if isinstance(task, tuple): # they've specified kwargs + start_task(task[0], **task[1]) # so pass those to start_task + else: # otherwise, just pass task_name start_task(task) def start_task(task_name, **kwargs): - """Start a given task in a new thread. Pass args to the task's run function.""" - print "Starting task '{}' in a new thread...".format(task_name) - + """Start a given task in a new thread. Pass args to the task's run() + function.""" + print "Starting task '{0}' in a new thread...".format(task_name) + try: - task = task_list[task_name] # get the class for this task, a subclass of BaseTask + task = task_list[task_name] except KeyError: - print "Couldn't find task '{}': wiki/tasks/{}.py does not exist.".format(task_name, task_name) + print ("Couldn't find task '{0}': wiki/tasks/{1}.py does not " + + "exist.").format(task_name, task_name) return - - task_thread = threading.Thread(target=lambda: task_wrapper(task, **kwargs)) # Normally we'd do task_wrapper(task, **kwargs), but because of threading we'd have to do Thread(target=task_wrapper, args=(task, **kwargs)), which doesn't work because the **kwargs is inside a tuple, not inside function params. Use lambda to get around the args=tuple nonsense - task_thread.name = "{} ({})".format(task_name, time.strftime("%b %d %H:%M:%S")) - task_thread.daemon = True # stop bot task threads automagically if the main bot stops + + task_thread = threading.Thread(target=lambda: task_wrapper(task, **kwargs)) + task_thread.name = "{0} ({1})".format(task_name, time.strftime( + "%b %d %H:%M:%S")) + + # stop bot task threads automagically if the main bot stops + task_thread.daemon = True + task_thread.start() def task_wrapper(task, **kwargs): @@ -73,7 +88,8 @@ def task_wrapper(task, **kwargs): try: task.run(**kwargs) except: - print "Task '{}' raised an exception and had to stop:".format(task.task_name) + print "Task '{0}' raised an exception and had to stop:".format( + task.task_name) traceback.print_exc() else: - print "Task '{}' finished without error.".format(task.task_name) + print "Task '{0}' finished without error.".format(task.task_name) From a06e35ecefa00d555195917147d899bc5b40af29 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 23 Jun 2011 12:47:22 -0400 Subject: [PATCH 025/692] moving IRC class modules (base_command.py, connection.py, data.py, rc.py) to irc/classes/ --- irc/classes/__init__.py | 4 ++++ irc/{ => classes}/base_command.py | 0 irc/{ => classes}/connection.py | 0 irc/{ => classes}/data.py | 0 irc/{ => classes}/rc.py | 0 irc/commands/afc_status.py | 2 +- irc/commands/calc.py | 2 +- irc/commands/chanops.py | 2 +- irc/commands/git.py | 6 ++++-- irc/commands/help.py | 3 +-- irc/commands/link.py | 2 +- irc/commands/tasks.py | 3 +-- irc/commands/test.py | 2 +- irc/frontend.py | 3 +-- irc/watcher.py | 3 +-- 15 files changed, 17 insertions(+), 15 deletions(-) create mode 100644 irc/classes/__init__.py rename irc/{ => classes}/base_command.py (100%) rename irc/{ => classes}/connection.py (100%) rename irc/{ => classes}/data.py (100%) rename irc/{ => classes}/rc.py (100%) diff --git a/irc/classes/__init__.py b/irc/classes/__init__.py new file mode 100644 index 0000000..b92db69 --- /dev/null +++ b/irc/classes/__init__.py @@ -0,0 +1,4 @@ +from base_command import * +from connection import * +from data import * +from rc import * diff --git a/irc/base_command.py b/irc/classes/base_command.py similarity index 100% rename from irc/base_command.py rename to irc/classes/base_command.py diff --git a/irc/connection.py b/irc/classes/connection.py similarity index 100% rename from irc/connection.py rename to irc/classes/connection.py diff --git a/irc/data.py b/irc/classes/data.py similarity index 100% rename from irc/data.py rename to irc/classes/data.py diff --git a/irc/rc.py b/irc/classes/rc.py similarity index 100% rename from irc/rc.py rename to irc/classes/rc.py diff --git a/irc/commands/afc_status.py b/irc/commands/afc_status.py index dd0248c..6a7f720 100644 --- a/irc/commands/afc_status.py +++ b/irc/commands/afc_status.py @@ -6,7 +6,7 @@ import json import re import urllib -from irc.base_command import BaseCommand +from irc.classes import BaseCommand class AFCStatus(BaseCommand): def get_hooks(self): diff --git a/irc/commands/calc.py b/irc/commands/calc.py index ceaca78..fbd26a1 100644 --- a/irc/commands/calc.py +++ b/irc/commands/calc.py @@ -5,7 +5,7 @@ import re import urllib -from irc.base_command import BaseCommand +from irc.classes import BaseCommand class Calc(BaseCommand): def get_hooks(self): diff --git a/irc/commands/chanops.py b/irc/commands/chanops.py index a2a9cc6..1bd7a8d 100644 --- a/irc/commands/chanops.py +++ b/irc/commands/chanops.py @@ -2,7 +2,7 @@ # Voice/devoice/op/deop users in the channel. -from irc.base_command import BaseCommand +from irc.classes import BaseCommand from core import config class ChanOps(BaseCommand): diff --git a/irc/commands/git.py b/irc/commands/git.py index a919904..4d09d9c 100644 --- a/irc/commands/git.py +++ b/irc/commands/git.py @@ -2,9 +2,11 @@ # Commands to interface with the bot's git repository; use '!git help' for sub-command list. -import shlex, subprocess, re +import shlex +import subprocess +import re -from irc.base_command import BaseCommand +from irc.classes import BaseCommand from core import config class Git(BaseCommand): diff --git a/irc/commands/help.py b/irc/commands/help.py index 1970337..54eefa2 100644 --- a/irc/commands/help.py +++ b/irc/commands/help.py @@ -2,8 +2,7 @@ # Generates help information. -from irc.base_command import BaseCommand -from irc.data import Data +from irc.classes import BaseCommand, Data from irc import command_handler class Help(BaseCommand): diff --git a/irc/commands/link.py b/irc/commands/link.py index 59f2d6e..4587451 100644 --- a/irc/commands/link.py +++ b/irc/commands/link.py @@ -4,7 +4,7 @@ import re -from irc.base_command import BaseCommand +from irc.classes import BaseCommand class Link(BaseCommand): def get_hooks(self): diff --git a/irc/commands/tasks.py b/irc/commands/tasks.py index 58050d0..5dba593 100644 --- a/irc/commands/tasks.py +++ b/irc/commands/tasks.py @@ -5,8 +5,7 @@ import threading import re -from irc.base_command import BaseCommand -from irc.data import * +from irc.classes import BaseCommand, Data, KwargParseException from wiki import task_manager from core import config diff --git a/irc/commands/test.py b/irc/commands/test.py index 69ecd2f..630a37f 100644 --- a/irc/commands/test.py +++ b/irc/commands/test.py @@ -4,7 +4,7 @@ import random -from irc.base_command import BaseCommand +from irc.classes import BaseCommand class Test(BaseCommand): def get_hooks(self): diff --git a/irc/frontend.py b/irc/frontend.py index 38d326a..56a6f17 100644 --- a/irc/frontend.py +++ b/irc/frontend.py @@ -13,8 +13,7 @@ from re import findall from core import config from irc import command_handler -from irc.connection import * -from irc.data import Data +from irc.classes import Connection, Data, BrokenSocketException connection = None diff --git a/irc/watcher.py b/irc/watcher.py index bbc17c9..c39f47c 100644 --- a/irc/watcher.py +++ b/irc/watcher.py @@ -11,8 +11,7 @@ channels in the IRC frontend. """ from core import config -from irc.connection import * -from irc.rc import RC +from irc.classes import Connection, RC, BrokenSocketException from irc import watcher_logic frontend_conn = None From 7311ae4bb897c5f09e041978406a0eb67ce988d9 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Tue, 5 Jul 2011 00:50:37 -0400 Subject: [PATCH 026/692] switching from XML config to JSON config - it's just much easier to parse and little easier on the eyes (not to mention shorter in length) --- .gitignore | 2 +- core/config.py | 345 +++++++++++++----------------------------------- core/main.py | 30 ++--- irc/commands/chanops.py | 2 +- irc/commands/git.py | 2 +- irc/commands/tasks.py | 6 +- irc/frontend.py | 23 ++-- irc/watcher.py | 9 +- wiki/task_manager.py | 4 +- 9 files changed, 135 insertions(+), 288 deletions(-) diff --git a/.gitignore b/.gitignore index 868c046..1e66a11 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ *.pyc # Ignore bot-specific config file: -config.xml +config.json # Ignore pydev's nonsense: .project diff --git a/core/config.py b/core/config.py index b1331ce..29c3fe1 100644 --- a/core/config.py +++ b/core/config.py @@ -1,74 +1,56 @@ # -*- coding: utf-8 -*- """ -EarwigBot's XML Config File Parser +EarwigBot's JSON Config File Parser This handles all tasks involving reading and writing to our config file, including encrypting and decrypting passwords and making a new config file from scratch at the inital bot run. Usually you'll just want to do "from core import config" and access config data -from within config's four global variables: +from within config's three global variables and one function: -* config.components -* config.wiki -* config.irc -* config.schedule +* config.components - a list of enabled components +* config.wiki - a dict of config information for wiki-editing +* config.irc - a dict of config information for IRC +* config.schedule() - returns a list of tasks scheduled to run now """ -from collections import defaultdict +import json from os import makedirs, path -from xml.dom import minidom -from xml.parsers.expat import ExpatError from lib import blowfish script_dir = path.dirname(path.abspath(__file__)) root_dir = path.split(script_dir)[0] -config_path = path.join(root_dir, "config.xml") +config_path = path.join(root_dir, "config.json") -_config = None # holds the parsed DOM object for our config file +_config = None # holds data loaded from our config file -# initialize our five global variables to store config data -components, wiki, irc, schedule, watcher = (None, None, None, None, None) +# set our three easy-config-access global variables to None +components, wiki, irc = (None, None, None) -class ConfigParseError(Exception): - """Base exception for when we could not parse the config file.""" - -class TypeMismatchError(ConfigParseError): - """A field does not fit to its expected type; e.g., an arbitrary string - where we expected a boolean or integer.""" - -class MissingElementError(ConfigParseError): - """An element in the config file is missing a required sub-element.""" - -class MissingAttributeError(ConfigParseError): - """An element is missing a required attribute to be parsed correctly.""" - -class Container(object): - """A class to hold information in a nice, accessable manner.""" - -def _load_config(): - """Load data from our XML config file (config.xml) into a DOM object.""" +def load_config(): + """Load data from our JSON config file (config.json) into _config.""" global _config - _config = minidom.parse(config_path) + with open(config_path, 'r') as fp: + try: + _config = json.load(fp) + except ValueError as error: + print "Error parsing config file {0}:".format(config_path) + print error + exit(1) def verify_config(): """Check to see if we have a valid config file, and if not, notify the user. If there is no config file at all, offer to make one; otherwise, exit.""" if path.exists(config_path): + load_config() try: - _load_config() - except ExpatError as error: - print "Could not parse config file {0}:\n{1}".format(config_path, - error) - exit() - else: - if not _config.getElementsByTagName("config"): - e = "Config file is missing a tag." - raise MissingElementError(e) - return are_passwords_encrypted() + return _config["encryptPasswords"] # are passwords encrypted? + except KeyError: + return False # assume passwords are not encrypted by default else: print "You haven't configured the bot yet!" choice = raw_input("Would you like to do this now? [y/n] ") @@ -77,235 +59,94 @@ def verify_config(): else: exit() -def make_new_config(): - """Make a new XML config file based on the user's input.""" - makedirs(config_dir) - - encrypt = raw_input("Would you like to encrypt passwords stored in " + - "config.xml? [y/n] ") - if encrypt.lower().startswith("y"): - is_encrypted = True - else: - is_encrypted = False - - return is_encrypted - -def are_passwords_encrypted(): - """Determine if the passwords in our config file are encrypted; return - either True or False, or raise an exception if there was a problem reading - the config file.""" - element = _config.getElementsByTagName("config")[0] - attribute = element.getAttribute("encrypt-passwords") - if not attribute: - return False - return attribute_to_bool(attribute, element, "encrypt-passwords") +def parse_config(key): + """Store data from our config file in three global variables for easy + access, and use the key to unencrypt passwords. Catch password decryption + errors and report them to the user.""" + global components, wiki, irc -def get_first_element(parent, tag_name): - """Return the first child of the parent element with the given tag name, or - return None if no child of that name exists.""" + load_config() # we might be re-loading unnecessarily here, but no harm in + # that! try: - return parent.getElementsByTagName(tag_name)[0] - except IndexError: - return None - -def get_required_element(parent, tag_name): - """Return the first child of the parent element with the given tag name, or - raise MissingElementError() if no child of that name exists.""" - element = get_first_element(parent, tag_name) - if not element: - e = "A <{0}> tag is missing a required <{1}> child tag.".format( - parent.tagName, tag_name) - raise MissingElementError(e) - return element - -def get_required_attribute(element, attr_name): - """Return the value of the attribute 'attr_name' in 'element'. If - undefined, raise MissingAttributeError().""" - attribute = element.getAttribute(attr_name) - if not attribute: - e = "A <{0}> tag is missing the required attribute '{1}'.".format( - element.tagName, attr_name) - raise MissingAttributeError(e) - return attribute - -def attribute_to_bool(value, element, attr_name): - """Return True if 'value' is 'true', '1', or 'on', return False if it is - 'false', '0', or 'off' (regardless of capitalization), or raise - TypeMismatchError() if it does match any of those. 'element' and - 'attr_name' are only used to generate the error message.""" - lcase = value.lower() - if lcase in ["true", "1", "on"]: - return True - elif lcase in ["false", "0", "off"]: - return False - else: - e = ("Expected a bool in attribute '{0}' of tag '{1}', but got '{2}'." - ).format(attr_name, element.tagName, value) - raise TypeMismatchError(e) - -def attribute_to_int(value, element, attr_name): - """Return 'value' after it is converted to an integer. If it could not be - converted, raise TypeMismatchError() using 'element' and 'attr_name' only - to give the user information about what happened.""" + components = _config["components"] + except KeyError: + components = [] + try: + wiki = _config["wiki"] + except KeyError: + wiki = {} try: - return int(value) - except ValueError: - e = ("Expected an integer in attribute '{0}' of tag '{1}', but got " + - "'{2}'.").format(attr_name, element.tagName, value) - raise TypeMismatchError(e) + irc = _config["irc"] + except KeyError: + irc = {} -def parse_config(key): - """A thin wrapper for the actual config parser in _parse_config(): catch - parsing exceptions and report them to the user cleanly.""" try: - _parse_config(key) - except ConfigParseError as error: - print "\nError parsing config file:" - print error - exit(1) + try: + if _config["encryptPasswords"]: + decrypt(key, "wiki['password']") + decrypt(key, "irc['frontend']['nickservPassword']") + decrypt(key, "irc['watcher']['nickservPassword']") + except KeyError: + pass except blowfish.BlowfishError as error: print "\nError decrypting passwords:" print "{0}: {1}.".format(error.__class__.__name__, error) exit(1) -def _parse_config(key): - """Parse config data from a DOM object into the four global variables that - store our config info. The key is used to unencrypt passwords stored in the - XML config file.""" - global components, wiki, irc, schedule - - _load_config() # we might be re-loading unnecessarily here, but no harm in - # that! - data = _config.getElementsByTagName("config")[0] - - components = parse_components(data) - wiki = parse_wiki(data, key) - irc = parse_irc(data, key) - schedule = parse_schedule(data) - -def parse_components(data): - """Parse everything within the XML tag of our config file. - The components object here will exist as config.components, and is a dict - of our enabled components: components[name] = True if it is enabled, False - if it is disabled.""" - components = defaultdict(lambda: False) # all components are disabled by - # default - element = get_required_element(data, "components") - - for component in element.getElementsByTagName("component"): - name = get_required_attribute(component, "name") - components[name] = True - - return components - -def parse_wiki(data, key): - """Parse everything within the tag of our XML config file.""" - pass - -def parse_irc_server(data, key): - """Parse everything within a tag.""" - server = Container() - connection = get_required_element(data, "connection") - - server.host = get_required_attribute(connection, "host") - server.port = get_required_attribute(connection, "port") - server.nick = get_required_attribute(connection, "nick") - server.ident = get_required_attribute(connection, "ident") - server.realname = get_required_attribute(connection, "realname") - - # convert the port from a string to an int - server.port = attribute_to_int(server.port, connection, "port") - - nickserv = get_first_element(data, "nickserv") - if nickserv: - server.nickserv = Container() - server.nickserv.username = get_required_attribute(nickserv, "username") - password = get_required_attribute(nickserv, "password") - if are_passwords_encrypted(): - server.nickserv.password = blowfish.decrypt(key, password) - else: - server.nickserv.password = password - else: - server.nickserv = None - - server.channels = list() - channels = get_first_element(data, "channels") - if channels: - for channel in channels.getElementsByTagName("channel"): - name = get_required_attribute(channel, "name") - server.channels.append(name) - - return server - -def parse_irc(data, key): - """Parse everything within the tag of our XML config file.""" - irc = Container() - - element = get_first_element(data, "irc") - if not element: - return irc - - servers = get_first_element(element, "servers") - if servers: - for server in servers.getElementsByTagName("server"): - server_name = get_required_attribute(server, "name") - if server_name == "frontend": - irc.frontend = parse_irc_server(server, key) - elif server_name == "watcher": - irc.watcher = parse_irc_server(server, key) - else: - print ("Warning: config file specifies a with " + - "unknown name '{0}'. Ignoring.").format(server_name) - - permissions = get_first_element(element, "permissions") - if permissions: - irc.permissions = dict() - for group in permissions.getElementsByTagName("group"): - group_name = get_required_attribute(group, "name") - irc.permissions[group_name] = list() - for user in group.getElementsByTagName("user"): - hostname = get_required_attribute(user, "host") - irc.permissions[group_name].append(hostname) - - return irc +def decrypt(key, item): + """Decrypt 'item' with blowfish.decrypt() using the given key and set it to + the decrypted result. 'item' should be a string, like + decrypt(key, "wiki['password']"), NOT decrypt(key, wiki['password'), + because that won't work.""" + global irc, wiki + try: + result = blowfish.decrypt(key, eval(item)) + except KeyError: + return + exec "{0} = result".format(item) -def parse_schedule(data): - """Store the element in schedule.data and the _schedule() - function as schedule.check().""" - schedule = Container() - schedule.check = _schedule - schedule.data = get_first_element(data, "schedule") - return schedule - -def _schedule(minute, hour, month_day, month, week_day): +def schedule(minute, hour, month_day, month, week_day): """Return a list of tasks that are scheduled to run at the time specified - by the function args. The schedule data comes from our config file's - tag, which is stored as schedule.data. Call this function with - config.schedule.check(args).""" - tasks = [] # tasks to run this turn, each as a tuple of (task_name, + by the function arguments. The schedule data comes from our config file's + 'schedule' field, which is stored as _config["schedule"]. Call this + function with config.schedule(args).""" + tasks = [] # tasks to run this turn, each as a tuple of either (task_name, # kwargs), or just task_name now = {"minute": minute, "hour": hour, "month_day": month_day, "month": month, "week_day": week_day} - for when in schedule.data.getElementsByTagName("when"): + try: + data = _config["schedule"] + except KeyError: + data = [] + for event in data: do = True for key, value in now.items(): - if when.hasAttribute(key): - req = when.getAttribute(key) - if attribute_to_int(req, when, key) != value: - do = False - break + try: + requirement = event[key] + except KeyError: + continue + if requirement != value: + do = False + break if do: - for task in when.getElementsByTagName("task"): - name = get_required_attribute(task, "name") - args = dict() - for key in task.attributes.keys(): - args[key] = task.getAttribute(key) - del args["name"] - if args: - tasks.append((name, args)) - else: - tasks.append(name) + try: + tasks.extend(event["tasks"]) + except KeyError: + pass return tasks + +def make_new_config(): + """Make a new config file based on the user's input.""" + makedirs(config_dir) + + encrypt = raw_input("Would you like to encrypt passwords stored in " + + "config.json? [y/n] ") + if encrypt.lower().startswith("y"): + is_encrypted = True + else: + is_encrypted = False + + return is_encrypted diff --git a/core/main.py b/core/main.py index 649e1f6..0b49842 100644 --- a/core/main.py +++ b/core/main.py @@ -77,7 +77,7 @@ def wiki_scheduler(): if time_diff < 60: # sleep until the next minute time.sleep(60 - time_diff) -def irc_frontend(components): +def irc_frontend(): """If the IRC frontend is enabled, make it run on our primary thread, and enable the wiki scheduler and IRC watcher on new threads if they are enabled.""" @@ -87,7 +87,7 @@ def irc_frontend(components): f_conn = frontend.get_connection() frontend.startup(f_conn) - if config.components["wiki_schedule"]: + if "wiki_schedule" in config.components: print "\nStarting wiki scheduler..." task_manager.load_tasks() t_scheduler = threading.Thread(target=wiki_scheduler) @@ -95,7 +95,7 @@ def irc_frontend(components): t_scheduler.daemon = True t_scheduler.start() - if config.components["irc_watcher"]: + if "irc_watcher" in config.components: print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=(f_conn,)) t_watcher.name = "irc-watcher" @@ -104,7 +104,7 @@ def irc_frontend(components): frontend.main() - if config.components["irc_watcher"]: + if "irc_watcher" in config.components: w_conn.close() f_conn.close() @@ -115,16 +115,16 @@ def run(): key = None config.parse_config(key) # load data from the config file and parse it # using the unlock key - components = config.components + enabled = config.components - if components["irc_frontend"]: # make the frontend run on our primary - irc_frontend(components) # thread if enabled, and enable additional - # components through that function + if "irc_frontend" in enabled: # make the frontend run on our primary + irc_frontend() # thread if enabled, and enable additional + # components through that function - elif components["wiki_schedule"]: # run the scheduler on the main - print "Starting wiki scheduler..." # thread, but also run the IRC - task_manager.load_tasks() # watcher on another thread iff it - if components["irc_watcher"]: # is enabled + elif "wiki_schedule" in enabled: # run the scheduler on the main + print "Starting wiki scheduler..." # thread, but also run the IRC + task_manager.load_tasks() # watcher on another thread iff it + if "irc_watcher" in enabled: # is enabled print "\nStarting IRC watcher..." t_watcher = threading.Thread(target=irc_watcher, args=()) t_watcher.name = "irc-watcher" @@ -132,9 +132,9 @@ def run(): t_watcher.start() wiki_scheduler() - elif components["irc_watcher"]: # the IRC watcher is our only enabled - print "Starting IRC watcher..." # component, so run its function only - irc_watcher() # and don't worry about anything else + elif "irc_watcher" in enabled: # the IRC watcher is our only enabled + print "Starting IRC watcher..." # component, so run its function only + irc_watcher() # and don't worry about anything else else: # nothing is enabled! print "No bot parts are enabled; stopping..." diff --git a/irc/commands/chanops.py b/irc/commands/chanops.py index 1bd7a8d..210a830 100644 --- a/irc/commands/chanops.py +++ b/irc/commands/chanops.py @@ -19,7 +19,7 @@ class ChanOps(BaseCommand): return False def process(self, data): - if data.host not in config.irc.permissions["admins"]: + if data.host not in config.irc["permissions"]["admins"]: self.connection.reply(data, "you must be a bot admin to use this command.") return diff --git a/irc/commands/git.py b/irc/commands/git.py index 4d09d9c..5c35739 100644 --- a/irc/commands/git.py +++ b/irc/commands/git.py @@ -23,7 +23,7 @@ class Git(BaseCommand): def process(self, data): self.data = data - if data.host not in config.irc.permissions["owners"]: + if data.host not in config.irc["permissions"]["owners"]: self.connection.reply(data, "you must be a bot owner to use this command.") return diff --git a/irc/commands/tasks.py b/irc/commands/tasks.py index 5dba593..7776db4 100644 --- a/irc/commands/tasks.py +++ b/irc/commands/tasks.py @@ -23,7 +23,7 @@ class Tasks(BaseCommand): def process(self, data): self.data = data - if data.host not in config.irc.permissions["owners"]: + if data.host not in config.irc["permissions"]["owners"]: self.connection.reply(data, "at this time, you must be a bot owner to use this command.") return @@ -115,9 +115,9 @@ class Tasks(BaseCommand): def get_main_thread_name(self): """Return the "proper" name of the MainThread; e.g. "irc-frontend" or "irc-watcher".""" - if config.components["irc_frontend"]: + if "irc_frontend" in config.components: return "irc-frontend" - elif config.components["wiki_schedule"]: + elif "wiki_schedule" in config.components: return "wiki-scheduler" else: return "irc-watcher" diff --git a/irc/frontend.py b/irc/frontend.py index 56a6f17..2a8537d 100644 --- a/irc/frontend.py +++ b/irc/frontend.py @@ -20,8 +20,9 @@ connection = None def get_connection(): """Return a new Connection() instance with information about our server connection, but don't actually connect yet.""" - cf = config.irc.frontend - connection = Connection(cf.host, cf.port, cf.nick, cf.nick, cf.realname) + cf = config.irc["frontend"] + connection = Connection(cf["host"], cf["port"], cf["nick"], cf["ident"], + cf["realname"]) return connection def startup(conn): @@ -66,7 +67,7 @@ def main(): data.msg = ' '.join(line[3:])[1:] data.chan = line[2] - if data.chan == config.irc.frontend.nick: + if data.chan == config.irc["frontend"]["nick"]: # this is a privmsg to us, so set 'chan' as the nick of the # sender, then check for private-only command hooks data.chan = data.nick @@ -81,7 +82,7 @@ def main(): # hardcode the !restart command (we can't restart from within # an ordinary command) if data.msg in ["!restart", ".restart"]: - if data.host in config.irc.permissions["owners"]: + if data.host in config.irc["permissions"]["owners"]: print "Restarting bot per owner request..." return @@ -89,11 +90,15 @@ def main(): connection.send("PONG %s" % line[1]) if line[1] == "376": # we've successfully connected to the network - ns = config.irc.frontend.nickserv - if ns: # if we're supposed to auth to nickserv, do that - connection.say("NickServ", "IDENTIFY %s %s" % (ns.username, - ns.password)) + try: # if we're supposed to auth to nickserv, do that + ns_username = config.irc["frontend"]["nickservUsername"] + ns_password = config.irc["frontend"]["nickservPassword"] + except KeyError: + pass + else: + connection.say("NickServ", "IDENTIFY {0} {1}".format( + ns_username, ns_password)) # join all of our startup channels - for chan in config.irc.frontend.channels: + for chan in config.irc["frontend"]["channels"]: connection.join(chan) diff --git a/irc/watcher.py b/irc/watcher.py index c39f47c..b031b20 100644 --- a/irc/watcher.py +++ b/irc/watcher.py @@ -19,8 +19,9 @@ frontend_conn = None def get_connection(): """Return a new Connection() instance with information about our server connection, but don't actually connect yet.""" - cf = config.irc.watcher - connection = Connection(cf.host, cf.port, cf.nick, cf.nick, cf.realname) + cf = config.irc["watcher"] + connection = Connection(cf["host"], cf["port"], cf["nick"], cf["ident"], + cf["realname"]) return connection def main(connection, f_conn=None): @@ -49,7 +50,7 @@ def main(connection, f_conn=None): # ignore messages originating from channels not in our list, to # prevent someone PMing us false data - if chan not in config.irc.watcher.channels: + if chan not in config.irc["watcher"]["channels"]: continue msg = ' '.join(line[3:])[1:] @@ -62,7 +63,7 @@ def main(connection, f_conn=None): # when we've finished starting up, join all watcher channels if line[1] == "376": - for chan in config.irc.watcher.channels: + for chan in config.irc["watcher"]["channels"]: connection.join(chan) def process(rc): diff --git a/wiki/task_manager.py b/wiki/task_manager.py index 3c37a63..de40db1 100644 --- a/wiki/task_manager.py +++ b/wiki/task_manager.py @@ -53,8 +53,8 @@ def load_class_from_file(f): def start_tasks(now=time.gmtime()): """Start all tasks that are supposed to be run at a given time.""" - tasks = config.schedule.check(now.tm_min, now.tm_hour, now.tm_mday, - now.tm_mon, now.tm_wday) # get list of tasks to run this turn + tasks = config.schedule(now.tm_min, now.tm_hour, now.tm_mday, now.tm_mon, + now.tm_wday) # get list of tasks to run this turn for task in tasks: if isinstance(task, tuple): # they've specified kwargs From e11cbffa92d12fb7812ddad159aeac759e209e0a Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 7 Jul 2011 01:05:16 -0400 Subject: [PATCH 027/692] uh, right... --- earwigbot.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 earwigbot.py diff --git a/earwigbot.py b/earwigbot.py old mode 100644 new mode 100755 From bea5a3bc7e4570481432fe5f60ce29f4da33e85c Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 7 Jul 2011 18:09:38 -0400 Subject: [PATCH 028/692] update message in README to be a tad more verbose (and to match the github description) --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9fc4c81..af1cbe3 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ [EarwigBot](http://toolserver.org/~earwig/earwigbot/) is a -[Python](http://python.org/) robot that edits Wikipedia. +[Python](http://python.org/) robot that edits +[Wikipedia](http://en.wikipedia.org/) and interacts with people over +[IRC](http://en.wikipedia.org/wiki/Internet_Relay_Chat). # History From 56738eaede3b645264a153b1e5855f3628288fa1 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Thu, 7 Jul 2011 18:12:04 -0400 Subject: [PATCH 029/692] argh - bugfix in lib/blowfish.py --- lib/blowfish.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/blowfish.py b/lib/blowfish.py index 25a1908..b02bd84 100644 --- a/lib/blowfish.py +++ b/lib/blowfish.py @@ -550,4 +550,4 @@ if __name__ == '__main__': cyphertext = raw_input("Enter a message to decrypt: ") print "\n" + decrypt(key, cyphertext) else: - print "Unknown action: '{0}'.".format(op) + print "Unknown action: '{0}'".format(action) From ffe05d34630e47c4901ef39467165d661f007bc7 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 16 Jul 2011 23:35:05 -0400 Subject: [PATCH 030/692] adding a !rights command to get user rights/groups --- irc/commands/rights.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 irc/commands/rights.py diff --git a/irc/commands/rights.py b/irc/commands/rights.py new file mode 100644 index 0000000..1ec5489 --- /dev/null +++ b/irc/commands/rights.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +""" +Retrieve a list of user rights for a given username via the API. +""" + +import json +import urllib + +from irc.classes import BaseCommand + +class Rights(BaseCommand): + def get_hooks(self): + return ["msg"] + + def get_help(self, command): + return "Retrieve a list of rights for a given username." + + def check(self, data): + if data.is_command and data.command in ["rights", "groups", "permissions", "privileges"]: + return True + return False + + def process(self, data): + if not data.args: + self.connection.reply(data, "what user do you want me to look up?") + return + + username = ''.join(data.args) + rights = self.get_rights(username) + if rights: + self.connection.reply(data, "the rights for user \x0302{0}\x0301 are {1}.".format(username, ', '.join(rights))) + else: + self.connection.reply(data, "the user x0302{0}\x0301 has no rights, or does not exist.".format(username)) + + def get_rights(self, username): + params = {'action': 'query', 'format': 'json', 'list': 'users', 'usprop': 'groups'} + params['ususers'] = username + data = urllib.urlencode(params) + raw = urllib.urlopen("http://en.wikipedia.org/w/api.php", data).read() + res = json.loads(raw) + try: + rights = res['query']['users'][0]['groups'] + except KeyError: # 'groups' not found, meaning the user does not exist + return None + try: + rights.remove("*") # remove the implicit '*' group given to everyone + except ValueError: # I don't expect this to happen, but if it does, be prepared + pass + return rights From b99a24fbbd8d3f1fef68cef5c9376bc5ec4f7acf Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 16 Jul 2011 23:37:04 -0400 Subject: [PATCH 031/692] forgot that I need to insert a space when joining data.args; typo fix --- irc/commands/rights.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/irc/commands/rights.py b/irc/commands/rights.py index 1ec5489..d456952 100644 --- a/irc/commands/rights.py +++ b/irc/commands/rights.py @@ -26,12 +26,12 @@ class Rights(BaseCommand): self.connection.reply(data, "what user do you want me to look up?") return - username = ''.join(data.args) + username = ' '.join(data.args) rights = self.get_rights(username) if rights: self.connection.reply(data, "the rights for user \x0302{0}\x0301 are {1}.".format(username, ', '.join(rights))) else: - self.connection.reply(data, "the user x0302{0}\x0301 has no rights, or does not exist.".format(username)) + self.connection.reply(data, "the user \x0302{0}\x0301 has no rights, or does not exist.".format(username)) def get_rights(self, username): params = {'action': 'query', 'format': 'json', 'list': 'users', 'usprop': 'groups'} From 413f6c840b339a1b0ccf43216576173088bb83e6 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 16 Jul 2011 23:38:36 -0400 Subject: [PATCH 032/692] saying user is redundant - removing --- irc/commands/rights.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/irc/commands/rights.py b/irc/commands/rights.py index d456952..31d9437 100644 --- a/irc/commands/rights.py +++ b/irc/commands/rights.py @@ -29,7 +29,7 @@ class Rights(BaseCommand): username = ' '.join(data.args) rights = self.get_rights(username) if rights: - self.connection.reply(data, "the rights for user \x0302{0}\x0301 are {1}.".format(username, ', '.join(rights))) + self.connection.reply(data, "the rights for \x0302{0}\x0301 are {1}.".format(username, ', '.join(rights))) else: self.connection.reply(data, "the user \x0302{0}\x0301 has no rights, or does not exist.".format(username)) From 12c71675d378ea4bf59a0409f87450a5d0d63470 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sun, 17 Jul 2011 01:04:04 -0400 Subject: [PATCH 033/692] adding a !remind command from old EarwigBot, which spawns a new thread that sleeps until its time is up, so impimplementing in !tasks list; {} -> {0}, etc in tasks.py for Python 2.6 support; stripping indentation on blank lines in tasks.py --- irc/commands/remind.py | 50 +++++++++++++++++++++++++++++++++++++++++++ irc/commands/tasks.py | 58 ++++++++++++++++++++++++++------------------------ 2 files changed, 80 insertions(+), 28 deletions(-) create mode 100644 irc/commands/remind.py diff --git a/irc/commands/remind.py b/irc/commands/remind.py new file mode 100644 index 0000000..6de1767 --- /dev/null +++ b/irc/commands/remind.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +""" +Set a message to be repeated to you in a certain amount of time. +""" + +import threading +import time + +from irc.classes import BaseCommand + +class Remind(BaseCommand): + def get_hooks(self): + return ["msg"] + + def get_help(self, command): + return "Set a message to be repeated to you in a certain amount of time." + + def check(self, data): + if data.is_command and data.command in ["remind", "reminder"]: + return True + return False + + def process(self, data): + if not data.args: + self.connection.reply(data, "please specify a time (in seconds) and a message in the following format: !remind