LOC-18 Deploy server with ansible
LOC-18 Deploy server with ansible

It could do with some tidying and some conditionals, but it's now possible to deploy the server with the ansible playbook.

file:a/README.md -> file:b/README.md
--- a/README.md
+++ b/README.md
@@ -14,6 +14,11 @@
 The default behaviour is a Multi-User Chat (MUC), however direct messaging between participants within a room is also supported.
 
 
+## Project Management
+
+Planned features, bugfixes etc can all be viewed at [project.bentasker.co.uk](https://projects.bentasker.co.uk/jira_projects/browse/LOC.html). Release notes are at [bentasker.co.uk](https://www.bentasker.co.uk/documentation/release-notes/91-localchat)
+
+
 
 
 
@@ -22,12 +27,12 @@
 
 ### Server
 
-`TODO`
+See [server/README.md](server/README.md)
 
 
 ### Client
 
-`TODO`
+See [client/README.md](client/README.md)
 
 
 

file:b/ansible/README.md (new)
--- /dev/null
+++ b/ansible/README.md
@@ -1,1 +1,9 @@
+LocalChat Ansible Playbook Instructions
+=========================================
 
+
+
+Dependancies
+----------------
+
+Requires ansible >= 2.2

--- /dev/null
+++ b/ansible/group_vars/localchat-servers.yml
@@ -1,1 +1,3 @@
+ansible_user: ansible
+ansible_become: true
 

--- /dev/null
+++ b/ansible/inventory/hosts
@@ -1,1 +1,4 @@
+[localchat-servers]
+192.168.7.253
 
+

--- /dev/null
+++ b/ansible/locaLchat.service
@@ -1,1 +1,15 @@
+[Unit]
+Description=LocalChat
+After=multi-user.target
 
+[Service]
+WorkingDirectory=/usr/local/localchat
+Type=idle
+ExecStart=/usr/bin/python LocalChat.py
+Restart=always
+RestartSec=3
+
+[Install]
+WantedBy=multi-user.target
+
+

--- /dev/null
+++ b/ansible/localchat-servers.retry
@@ -1,1 +1,2 @@
+192.168.7.253
 

--- /dev/null
+++ b/ansible/localchat-servers.yml
@@ -1,1 +1,7 @@
+---
 
+-   hosts: localchat-servers
+    roles:
+        - localchat-server
+
+

--- /dev/null
+++ b/ansible/roles/localchat-server/defaults/main.yml
@@ -1,1 +1,4 @@
+localchat_server_install_path: /usr/local/src/localchat
+localchat_server_install_ver: 0.0.2.1
 
+

--- /dev/null
+++ b/ansible/roles/localchat-server/handlers/main.yml
@@ -1,1 +1,14 @@
+---
 
+# Handlers
+
+
+
+- name: Start service
+  # See above.
+  command: systemctl start localchat.service
+
+- name: reload systemd
+  command: systemctl daemon-reload
+
+

--- /dev/null
+++ b/ansible/roles/localchat-server/tasks/main.yml
@@ -1,1 +1,46 @@
+---
 
+- name: Install Utils
+  apt: name={{item}} state=installed
+  with_items:
+    - python-pip
+    - python-sqlite
+    - unzip
+  tags: deps
+
+- name: Install Python Dependancies
+  pip: name={{item}} state=present
+  with_items:
+    - flask
+    - werkzeug
+    - bcrypt
+    - gnupg
+    - pyopenssl
+  tags: deps
+
+
+- name: Create install dir
+  file: path={{localchat_server_install_path}} state=directory
+  
+- name: Download and install Server
+  unarchive:
+    src: "https://github.com/bentasker/LocalChat/archive/v{{localchat_server_install_ver}}.zip"
+    dest: "{{localchat_server_install_path}}"
+    remote_src: yes
+  
+- name: Symlink latest
+  file:
+    src: "{{localchat_server_install_path}}/LocalChat-{{localchat_server_install_ver}}/server/LocalChat.py"
+    dest: "{{localchat_server_install_path}}/LocalChat.py"
+    state: link
+    
+- name: Create Unit File
+  template: src=localchat.service dest=/etc/systemd/system/localchat.service
+  notify: reload systemd
+
+
+- name: Start server
+  command: systemctl start localchat
+
+
+

--- /dev/null
+++ b/ansible/roles/localchat-server/templates/localchat.service
@@ -1,1 +1,14 @@
+[Unit]
+Description=LocalChat
+After=multi-user.target
 
+[Service]
+WorkingDirectory={{localchat_server_install_path}}
+Type=idle
+ExecStart=/usr/bin/python LocalChat.py
+Restart=always
+RestartSec=3
+
+[Install]
+WantedBy=multi-user.target
+

file:b/ansible/site.yml (new)
--- /dev/null
+++ b/ansible/site.yml
@@ -1,1 +1,2 @@
+- include: localchat-servers.yml
 

--- a/client/LocalChatClient.py
+++ b/client/LocalChatClient.py
@@ -459,7 +459,7 @@
 similar to cmd.Cmd in standard library
 just extend with do_something  method to handle your commands"""
 
-    def __init__(self,quit_commands=['q','quit','exit'], help_commands=['help','?', 'h']):
+    def __init__(self,quit_commands=['/q','/quit','/exit'], help_commands=['/help','/?', '/h']):
         self._quit_cmd=quit_commands
         self._help_cmd=help_commands
         
@@ -594,11 +594,15 @@
                     c.output('To join the room, they should do /join %s %s:%s %s' %(n[0],n[1],n[2],n[3]))
                     return                                        
                     
+            if cmd in ["help",'h','?']:
+                return self.help(args[0] if args else None)
+            
+            if cmd in ["exit",'q','quit']:
+                return Commander.Exit
+            
 
         if cmd in self._quit_cmd:
             return Commander.Exit
-        elif cmd in self._help_cmd:
-            return self.help(args[0] if args else None)
         elif hasattr(self, 'do_'+cmd):
             return getattr(self, 'do_'+cmd)(*args)
         else:
@@ -614,6 +618,9 @@
             hc ='|'.join(self._help_cmd)
             res='Type [%s] to quit program\n' % qc
             res += """Available commands: 
+
+            /h                                                          Print this help text
+
             
             /join [room] [password] [username]                          Join a room
             /leave                                                      Leave current room
@@ -622,6 +629,7 @@
             
             /room invite [user]                                         Invite a user into the current room
             /me [string]                                                Send an 'action' instead of a message
+            /msg [user] message                                         Send a direct message to [user]
             
             Room Admin commands:
             

file:b/client/README.md (new)
--- /dev/null
+++ b/client/README.md
@@ -1,1 +1,85 @@
+# LocalChat Client
 
+
+## About
+
+Localchat is a simple and lightweight chat application. It's primary purpose is to provide a means to have a multi-user Off-The-Record transient chat, minimising the likelihood that anyone but the chat participants has even a record that the chat took place.
+
+This client uses basic End To End encryption (currently using PGP as the encryption mechanism), and the server holds encrypted payloads in memory only (to ensure the ciphertext doesn't end up captured on the hosting provider's SAN for a time). 
+
+The default behaviour is a Multi-User Chat (MUC), however direct messaging between participants within a room is also supported.
+
+
+
+
+## Dependancies
+
+The following Python modules are required (other client dependancies should all already be present so long as you have python installed)
+
+* urllib2
+* urwid
+* gnupg
+
+
+
+
+
+## Usage Instructions
+
+Commands are IRC like:
+
+            /help                                                       Print Usage information
+
+            /join [room] [password] [username]                          Join a room
+            /leave                                                      Leave current room
+            /room create [roomname] [roompass] [admin user]             New room management
+
+
+            /room invite [user]                                         Invite a user into the current room
+            /me [string]                                                Send an 'action' instead of a message
+            /msg [user] message                                         Send a direct message to [user]
+
+            Room Admin commands:
+
+            /kick [user]                                                Kick a user out of the room (they can return)
+            /ban [user]                                                 Kick a user out and disinvite them (they cannot return)
+            /room close [roompass]                                      Kick all users out and close the room
+
+
+            /exit                                                       Quit the client
+
+
+
+## Commandline Arguments
+
+The client takes a limited number of commandline arguments. By default, none are needed, but depending on your deployment methodology, some of the following may be required.
+
+
+    ./LocalChatClient.py [--verify] [server]
+    
+
+When `--verify` is present, SSL certificate verification will be enabled (which means the server must present a certificate trusted by your system and valid for the server's address. By default that's not the case).
+
+If specified, `server` should be the last argument and must be of the format `https://[servername/ip[:port]]/[path]` (port is optional, default is `8090`).
+
+See the main [README](../README.md) for examples of deployments where these flags may be required.
+
+
+
+
+## Client Message API
+
+To send and receive messages, the client uses the [Server API](../docs/server-api.md), however, messages are contained within an encrypted payload that the server cannot see into. In order to be compatible with this client, message payloads need to be formed as a JSON encapsulated string with the following structure
+
+    {
+        "text":"[message text]",
+        "verb":[message verb]
+    }
+
+Message verbs were defined in [LOC-16](https://projects.bentasker.co.uk/jira_projects/browse/LOC-16.html). The default is `say` and any unrecognised verbs will be treated as such - an ordinary message. 
+
+The verb `do` will cause the client to print a `/me` message:
+
+            ** ben writes documentation **
+
+Once the JSON string has been generated, it should be PGP encrypted using the room key as a passphrase. The client uses Symmetric AES-256 encryption when encrypting, but will support decrypting anything that the Python PGP bindings support.

--- /dev/null
+++ b/docs/server-api.md
@@ -1,1 +1,323 @@
-
+Server API
+============
+
+All requests to the server are placed with the `POST` method, using a JSON request body
+
+The basic structure is
+
+    {
+        "action":"[api action]",
+        "payload": [json payload]
+    }
+
+Which, if successful, will result in a `HTTP 200` and a JSON encapsulated response body.
+
+----
+
+Response Codes
+---------------
+
+The following HTTP statuses may be returned
+
+* `200` - Request was successful
+* `400` - Invalid request
+* `403` - Authentication Invalid/Permission Denied
+* `500` - Server had an issue
+
+----
+
+Authentication
+---------------
+
+Authentication is performed on a per-room basis, so certain calls (such as `createRoom`) are currently entirely unauthenticated (a form of auth may be introduced for those later).
+
+User's are required to authenticate themselves (via password) when they attempt to enter a room with a `joinRoom` call. If that call is successful then a session key will be provided in the response. This must be embedded into every payload (as attribute `sesskey`) after that.
+
+The server uses `bcrypt` for storing authentication credentials.
+
+----
+
+Supported Actions
+-------------------
+
+
+### banUser
+
+Can only be called by the room admin, kicks a user out of the room, and does not allow them to return (unless re-invited)
+
+    {
+        "action":"banUser",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "user": user,
+                    "kick": [user to kick],
+                    "sesskey": sessionkey
+        }
+    }
+
+*Response*
+
+If successful, the value of `status` will be `ok` and the kicked user's session will be terminated and their user record removed. A message will be pushed to the room by `SYSTEM` to note that that user has been kicked and banned.
+
+If the requesting user lacks the privileges to kick a user, `SYSTEM` will push a message to warn that `user` tried to ban `tokick`.
+
+----
+
+### closeRoom
+
+This can only be successfully called by the room's owner. `closeRoom` will close the current room, remove all associated messages, sessions and user accounts.
+
+
+    {
+        "action":"closeRoom",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "user": user,
+                    "sesskey": sessionkey
+        }
+    }
+
+*Response*
+
+If successful, the value of `status` will be `ok`.
+
+Rooms should always be closed when they are no longer required. The server will (by default) automatically close inactive rooms after a period, but this is intended as a safety net (in case the admin gets disconnected and cannot reconnect for some reason).
+
+----
+
+### createRoom
+
+This is used to create a room. Calls are currently unauthenticated because user accounts are tied to a room rather than existing in a global namespace (this is done to limit the risk of a list of possible users sitting on the server until they're likely to be needed).
+
+    {
+        "action":"createRoom",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "owner": [name of user],
+                    "pass": password
+        }
+    }
+
+When creating a room, we specify the username of the user who will be the room owner/admin, and the password they will use to join the room. In the background this will set up the requisite user account.
+
+
+*Response*
+
+If the room is successfully created, the value of `status` will be `ok`. The roomname will also be confirmed back as the attribute `name`.
+
+The user will then need to call `joinRoom` in order to enter the room (the client could do this automatically, but the current client version does not).
+
+----
+
+### inviteUser
+
+Used to invite a user into the current room. Can be called by admin's and users alike (`SYSTEM` will push a message into the room to notify others of the invite)
+
+    {
+        "action":"inviteUser",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "user": user,
+                    "invite": [user to invite],
+                    "pass": [new users pass]
+                    "sesskey": sessionkey
+        }
+    }
+
+When inviting a user, we need to specify their username as `invite` and their authentication password as `pass`
+
+*Response*
+
+If successful, the value of `status` will be `ok`. `SYSTEM` will also push a message into the room that `user` invited `invite`
+
+----
+
+### joinRoom
+
+Used to enter a room.
+
+When the user was invited to the room, a password will have been set for them (the supplied client currently auto-generates that password), it will need to be provided for the user to authenticate.
+
+    {
+        "action":"joinRoom",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "userpass": password,
+                    "user": user
+        }
+    }
+
+*Response*
+
+If authentication is successful, the response will include a number of details that the client will need to take note of for future requests
+
+    {
+        "status": "ok",
+        "last": last,
+        "session": sessionkey,
+        "syskey": systemkey
+    }
+    
+The value `last` is the ID of the latest message in the room you've just joined. It should be included in `pollMsg` calls.
+
+The value `sessionkey` is a server generated sessionkey. It must be included in the payload of all future requests (it's used to help authenticate those requests).
+
+The value `syskey` is a decryption passphrase. The server's internal user `SYSTEM` will E2E encrypt any messages it pushes into rooms, this is the key you should use to decrypt those messages.
+
+----
+
+### kickUser
+
+Can only be called by the room admin, kicks a user out of the room (but allows them to return). Useful where you think a user's session has hung (for example)
+
+    {
+        "action":"kickUser",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "user": user,
+                    "kick": [user to kick],
+                    "sesskey": sessionkey
+        }
+    }
+
+*Response*
+
+If successful, the value of `status` will be `ok` and the kicked user's session will be terminated. A message will be pushed to the room by `SYSTEM` to note that that user has been kicked.
+
+If the requesting user lacks the privileges to kick a user, `SYSTEM` will push a message to warn that `user` tried to kick `tokick`.
+
+----
+
+### leaveRoom
+
+Used to leave the current room
+
+    {
+        "action":"leaveRoom",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "user": user,
+                    "sesskey": sessionkey
+        }
+    }
+
+*Response*
+
+If successful, the value of `status` will be `ok`. Client's should then disable any automated message polling they are running.
+
+----
+
+### pollMsg
+
+Used to check whether there are any messages since the last the client received. It will return room-wide messages and direct messages addressed to the polling user.
+
+Client provides the ID of the last message they've received, as well as the room they're polling. Where this is the first request, `last` should be 0
+
+    {
+        "action":"pollMsg",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "mylast": "[last]",
+                    "user": user,
+                    "sesskey": sessionkey
+        }
+    }
+
+
+*Response*
+
+If there are no messages, then the response status will be `unchanged`.
+If a specific error is being returned, the response status will be `errmessage` - you should disable any automatic polling and the print the content of `text`
+
+If status is `updated` then messages have been returned:
+
+    {
+        "status": "updated",
+        "messages" : [
+                        [msgid,msgtext,timestamp,fromuser,touser],
+                        [msgid,msgtext,timestamp,fromuser,touser]    
+        ]
+
+    }
+
+Once the client has processed the received messages, the value of `last` in the next `pollMsg` request should be the maximum ID in the resultset.
+
+----
+
+### sendDirectMsg
+
+Used to send a message to a specific user within the room. The message will not be visible to other room occupants.
+
+    {
+        "action":"sendDirectMsg",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "msg": "[message payload]",
+                    "to": recipient
+                    "user": user,
+                    "sesskey": sessionkey
+        }
+    }
+
+The message payload is encrypted and base64 encoded by the client, so the server only sees a base64 string. 
+
+However, to keep compatability with the supplied client, your message payload (prior to encryption) should be a JSON encapsulated string of the format
+
+        msg = {
+            'user': user,
+            'text': msg,
+            "verb": verb
+            }
+
+This should then be PGP encrypted using the room passphrase, and then base64 encoded for embedding into the API payload.
+            
+Where `verb` is one of `do` or `say` (other values will be treated as `say` by the supplied client).
+
+
+*Response*
+
+If message sending is successful, the response will contain `status:"ok"`
+
+----
+
+### sendMsg
+
+Used to send a message to the entire room
+
+    {
+        "action":"sendMsg",
+        "payload": {    
+                    "roomName": "[name of room]",
+                    "msg": "[message payload]",
+                    "user": user,
+                    "sesskey": sessionkey
+        }
+    }
+
+The message payload is encrypted and base64 encoded by the client, so the server only sees a base64 string. 
+
+However, to keep compatability with the supplied client, your message payload (prior to encryption) should be a JSON encapsulated string of the format
+
+        msg = {
+            'user': user,
+            'text': msg,
+            "verb": verb
+            }
+
+This should then be PGP encrypted using the room passphrase, and then base64 encoded for embedding into the API payload.
+            
+Where `verb` is one of `do` or `say` (other values will be treated as `say` by the supplied client).
+
+
+*Response*
+
+If message sending is successful, the response will contain `status:"ok"`
+
+
+----
+
+
+
+
+    
+    

--- a/server/LocalChat.py
+++ b/server/LocalChat.py
@@ -73,7 +73,6 @@
             print "WARNING - Messages will be written to disk"
 
 
-
     def createDB(self):
         ''' Create the in-memory database ready for use 
         '''
@@ -139,7 +138,6 @@
         thread.start_new_thread(taskScheduler,(self.cronpass,self.bindpoint))
 
 
-
     def processSubmission(self,reqjson):
         ''' Process an incoming request and route it to
         the correct function
@@ -197,17 +195,12 @@
         elif reqjson['action'] == 'pollMsg':
             return self.fetchMsgs(reqjson)
          
-        
-        
-        
-        
 
     def decrypt(self,msg):
         ''' This is currently just a placeholder
         Will be updated later
         '''
         return msg
-
 
 
     def createRoom(self,reqjson):
@@ -267,7 +260,6 @@
             }
         
 
-
     def closeRoom(self,reqjson):
         ''' Close a room.
         
@@ -305,10 +297,6 @@
         self.conn.commit()
         
         return { "status" : "ok" }
-    
-        
-           
-        
 
 
     def inviteUser(self,reqjson):
@@ -345,8 +333,7 @@
         return {
                 "status":'ok'
             }
-        
-    
+
     
     def kickUser(self,reqjson,ban=False):
         ''' Kick a user out of room
@@ -369,8 +356,6 @@
         
         if not n:
             return self.returnFailure(403)
-        
-        
         
         self.cursor.execute("UPDATE users set active=0 where room=? and username=?",(room,reqjson["payload"]["kick"]))
         
@@ -388,9 +373,8 @@
             self.pushSystemMsg("User %s banned %s from the room" % (reqjson['payload']['user'],reqjson['payload']['kick']),room,'syswarn')
             
         return { "status" : "ok" }
-    
-
-    
+
+
     def processjoinRoom(self,reqjson):
         ''' Process a request from a user to login to a room
         
@@ -403,12 +387,10 @@
             if i not in reqjson['payload']:
                 return self.returnFailure(400)
                 
-        
         room = self.getRoomID(reqjson['payload']["roomName"])
         
         if not room:
             return self.returnFailure(400)
-        
         
         if reqjson["payload"]["user"] == "SYSTEM":
             return self.returnFailure(403)
@@ -419,13 +401,11 @@
         
         if not r:
             return { "status": "NOK" }
-        
         
         # Now we need to verify they've supplied a correct password for that user
         stored = r[2].encode("utf-8")
         if stored != bcrypt.hashpw(reqjson['payload']['userpass'].encode('utf-8'),stored):
             return self.returnFailure(403)
-        
             
         # Tidy older messages away.
         #
@@ -435,15 +415,12 @@
         # to scroll up and down in their client anyway
         self.tidyMsgs(time.time()-10,room)
         
-        
         # Push a message to the room to note that the user joined
         msgid = self.pushSystemMsg("User %s joined the room" % (reqjson['payload']['user']),room)
-
 
         # If we're in testing mode, push a warning so the new user can see it
         if self.testingMode:
             msgid = self.pushSystemMsg("Server is in testing mode. Messages are being written to disk",room,'syswarn')
-
 
         # Check the latest message ID for that room
         self.cursor.execute("SELECT id from messages WHERE room=? and id != ? ORDER BY id DESC",(room,msgid))
@@ -457,15 +434,14 @@
         # Mark the user as active in the users table
         self.cursor.execute("UPDATE users set active=1 where username=? and room=?", (reqjson['payload']['user'],room))
         
-        
         # Create a session for the user
         sesskey = "%s-%s" % (reqjson['payload']["roomName"],self.genSessionKey())
         self.cursor.execute("INSERT INTO sessions (username,sesskey) values (?,?)", (reqjson['payload']['user'],sesskey))
         self.conn.commit()
                 
         return {"status":"ok","last":last,"session":sesskey,"syskey":self.syskey}
-        
-        
+
+
     def processleaveRoom(self,reqjson):
         ''' Process a user's request to leave a room
         '''
@@ -491,8 +467,8 @@
         # Push a message to the room to note they left
         self.pushSystemMsg("User %s left the room" % (reqjson['payload']['user']),room)
         return {"status":"ok"}
-    
-    
+
+
     def sendMsg(self,reqjson):
         ''' Push a message into a room
         
@@ -502,7 +478,6 @@
         
         if not self.validateUser(reqjson['payload']):
             return self.returnFailure(403)
-        
         
         if "roomName" not in reqjson['payload'] or "msg" not in reqjson['payload']:
             return self.returnFailure(400)
@@ -511,8 +486,7 @@
         print room
         if not room:
             return self.returnFailure(400)
-
-            
+        
         self.cursor.execute("INSERT INTO messages (ts,room,msg,user) VALUES (?,?,?,?)",(time.time(),room,reqjson['payload']['msg'],reqjson['payload']['user']))
         msgid = self.cursor.lastrowid
         self.conn.commit()
@@ -525,7 +499,6 @@
             last = 0
         else:
             last = r[0]
-        
         
         # Update the last activity field in the DB
         # See LOC-11
@@ -537,7 +510,6 @@
                 "msgid" : msgid,
                 "last" : last
             }
-        
 
 
     def sendDirectMsg(self,reqjson):
@@ -587,10 +559,8 @@
                 "msgid" : msgid,
                 "last" : last
             }
-        
-
-
-        
+
+
     def fetchMsgs(self,reqjson):
         ''' Check to see if there are any new messages in the room
         
@@ -605,7 +575,6 @@
         print room
         if not room:
             return self.returnFailure(400)
-
 
         if not self.validateUser(reqjson['payload']):
             return self.returnFailure(403,reqjson['payload'],room)
@@ -627,18 +596,13 @@
         return {"status":"updated",
                 "messages" : r
                 }
-    
-    
-        
-        
-        
-    
+
+
     def validateUser(self,payload):
         ''' Placeholder for now. Auth will be handled in more depth later
         '''
         if "user" not in payload or "roomName" not in payload:
             return False
-        
         
         # Validate the session information
         self.cursor.execute("SELECT username from sessions where username=? and sesskey=?",(payload['user'],payload['sesskey']))
@@ -647,13 +611,10 @@
         if not r:
             return False
         
-        
         room = self.getRoomID(payload["roomName"])
         if not room:
             return False        
         
-        
-        
         # Check whether the user has been marked as active
         self.cursor.execute("SELECT username, room from users where username=? and room=? and active=1",(payload['user'],room))
         r = self.cursor.fetchone()
@@ -664,7 +625,6 @@
         return True
 
 
-    
     def getRoomID(self,roomname):
         ''' Get a room's ID from its name
         '''
@@ -676,7 +636,6 @@
             return False
         
         return r[0]
-    
 
 
     def triggerClean(self,reqjson):
@@ -697,8 +656,7 @@
         self.autoCloseRooms()
         
         return {'status':'ok'}
-        
-        
+
 
     def tidyMsgs(self,thresholdtime,room=False):
         ''' Remove messages older than the threshold time
@@ -717,8 +675,6 @@
         self.cursor.execute("DELETE FROM failuremsgs  where expires < ?",(time.time(),))
 
 
-
-
     def autoCloseRooms(self):
         ''' Automatically close any rooms that have been sat idle for too long
         '''
@@ -734,10 +690,6 @@
             self.cursor.execute("DELETE FROM sessions where sesskey like ?", (r[1] + '-%',))
             self.cursor.execute("DELETE FROM rooms where id=?",(r[0],))
             self.conn.commit()
-            
-            
-        
-
 
 
     def pushSystemMsg(self,msg,room,verb="sysinfo"):
@@ -769,8 +721,6 @@
         '''
         self.cursor.execute("INSERT INTO failuremsgs (username,room,expires,msg) values (?,?,?,?)",(user,room,time.time() + 300,msg))
         self.conn.commit()
-        
-        
 
 
     def returnFailure(self,status,reqjson=False,room=False):
@@ -796,9 +746,7 @@
             self.conn.commit()
             return {"status":"errmessage","text":r[0]}
         
-        
         return status
-        
 
 
     def encryptSysMsg(self,msg):
@@ -809,17 +757,15 @@
             more info.
         
         '''
-        
-        crypted = self.gpg.encrypt(msg,None,passphrase=self.syskey,symmetric="AES256",armor=False)
+
+        crypted = self.gpg.encrypt(msg,None,passphrase=self.syskey,symmetric="AES256",armor=False,encrypt=False)
         return crypted.data.encode('base64')
-        
 
 
     def genSessionKey(self,N=48):
         return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits + '/=?&@#%^()+,.<>:!').encode('utf-8') for _ in range(N))
 
 
-
     def genpassw(self,N=16):
         ''' Generate a random string of chars to act as an encryption password
         '''
@@ -827,10 +773,8 @@
         return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits).encode('utf-8') for _ in range(N))
 
 
-
 # Create the scheduler function
 def taskScheduler(passw,bindpoint):
-    
     
     # Ignore cert errors
     ctx = ssl.create_default_context()
@@ -853,12 +797,8 @@
             # Don't let the thread abort just because one request went wrong
             continue
 
-    
-
 
 if __name__ == '__main__':
-    
-    # These will be handled properly later
     passw = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits).encode('utf-8') for _ in range(64))
     bindpoint = "https://127.0.0.1:8090" 
     purgeinterval = 600 # Wipe messages older than 10 mins
@@ -877,14 +817,9 @@
     # as well as the URL it should POST to
     msghandler = MsgHandler(passw,bindpoint,purgeinterval,closethresh,testingmode)
 
-
     # Bind to PORT if defined, otherwise default to 8090.
+    #
+    # This will likely become a CLI argument later
     port = int(os.environ.get('PORT', 8090))
-    app.run(host='0.0.0.0', port=port,debug=True,ssl_context='adhoc')
-
-
-
-
-
-
-
+    app.run(host='127.0.0.1', port=port,ssl_context='adhoc',threaded=False)
+

file:b/server/README.md (new)
--- /dev/null
+++ b/server/README.md
@@ -1,1 +1,50 @@
+# LocalChat Server
 
+
+## About
+
+Localchat is a simple and lightweight chat application. It's primary purpose is to provide a means to have a multi-user Off-The-Record transient chat, minimising the likelihood that anyone but the chat participants has even a record that the chat took place.
+
+It binds to the loopback adapter, and uses ad-hoc SSL to ensure that chat messages aren't available to anyone capable of sniffing loopback traffic. Where clients are remote, there are a number of possible deployment options, see [The main README](../README.md) for more information on these.
+
+The internal database is stored in memory only, to ensure that metadata isn't written to (and therefore recoverable from) disk.
+
+It's intended to be incredibly lightweight, so is provided as a single Python file rather than being broken out into multiple files. Although it can support a reasonable number of active clients, it *is* a single threaded application and isn't designed to support 1000's of active users.
+
+
+
+
+## Dependancies
+
+The following non-standard modules are required
+
+* flask
+* urllib2
+* sqlite3
+* bcrypt
+* gnupg
+
+
+
+## Usage Instructions
+
+To start the server, simply run it
+
+    ./LocalChat.py
+    
+
+## Commandline Arguments
+
+The server takes a limited number of commandline arguments. By default, none are needed.
+
+
+    ./LocalChat.py [--testing-mode-enable]
+    
+
+When `--testing-mode-enable` is present, the internal database is written to disk rather than being kept in memory. This is for testing purposes only, and is outright dangerous for use in production. When this mode is enabled, whenever a user joins a room, `SYSTEM` will push a message to warn the room that messages are being written to disk. Testing mode also changes purge thresholds to a lower number so that the automated cleans will complete in a time more conduicive to testing. *Do Not* use this argument without very, very good reason.
+
+
+
+
+
+