Ejemplo n.º 1
0
def setHTML():
    page = HTMLPage()

    page.addLine("<h1>Set password</h1>", False)
    page.addLine("<form action='setpwd' method='get'>", False)
    page.addLine("<input type='password' name='pwd' id='focus' />")
    page.addLine("<input type='submit' class='button' value='Set password' />", False)

    return page.getPage()
Ejemplo n.º 2
0
def connectionErrorPage():
    """Returns page for connection error."""

    page = HTMLPage()
    page.addLine(u"<h1>Error</h1>", False)
    page.addLine(u"Can't connect to bitmessage daemon!")
    return page.getPage()
Ejemplo n.º 3
0
    def do_GET(self):
        global sessionID

        self.send_response(200)
        self.send_header('Content-type', 'text/html')

        authenticated = False

        #Session Management
        if self.path.startswith("/pwd"):
            query = parseQuery(self.path)
            try:
                pwd = query["pwd"][0]
            except:
                pwd = ""

            if password.isCorrect(pwd):
                sessionID = urandom(16).encode('base64').strip()
                self.send_header("Set-Cookie", "sessionID=" + sessionID)
                authenticated = True
                self.path = "/inbox"
                sleep(1) #To slow down brutforce
            else:
                self.wfile.write(password.enterHTML(True))
                sleep(1) #To slow down brutforce
                return


        if self.path.startswith("/setpwd") and not password.isSet():
            query = parseQuery(self.path)
            try:
                pwd = query["pwd"][0]
                password.set(pwd)
                authenticated = True
            except:
                authenticated = False

        if self.path.startswith("/logout"):
            sessionID = None

        if sessionID and not authenticated:
            try:
                cookie = Cookie.SimpleCookie(self.headers.getheader("cookie"))
                if sessionID == cookie['sessionID'].value:
                    authenticated = True
            except:
                authenticated = False

        self.end_headers()

        if not authenticated:
            if password.isSet():
                self.wfile.write(password.enterHTML())
            else:
                self.wfile.write(password.setHTML())
            return

        #End session management. 
        #The following code should only be executed when the user has passed authentication!

        if (not getPages.apiIsInit):
            error = getPages.initApi();

            if (error):
                self.wfile.write(error)
                return
                
        if self.path.startswith("/inbox") or self.path == "/":
            self.wfile.write(getPages.inbox())

        elif self.path.startswith("/outbox"):
            self.wfile.write(getPages.outbox())

        elif self.path.startswith("/composer"):
            query = parseQuery(self.path)
            toAddress = ""
            subject = ""
            text = ""
            try:
                if query.has_key("to"):
                    toAddress = query["to"][0]
                if query.has_key("subject"):
                    subject = query["subject"][0]
                if query.has_key("text"):
                    text = query["text"][0]
            except:
                pass
                
            self.wfile.write(getPages.composeMsg(toAddress, subject, text))

        elif self.path.startswith("/sendmsg"):
            query = parseQuery(self.path)
            
            try:
                toAddress = query["to"][0]
                fromAddress = query["from"][0]
                subject = query["subject"][0]
                text = query["text"][0]
            except:
                page = HTMLPage()
                page.addLine("<h1>Error while parsing message.")
                page.addLine("Message NOT send!</h1>")
                self.wfile.write(page.getPage())
                return

            self.wfile.write(getPages.sendMsg(toAddress, fromAddress, subject, text))

        elif self.path.startswith("/subscriptions"):
            self.wfile.write(getPages.subscriptions())

        elif self.path.startswith("/unsubscribe"):
            query = parseQuery(self.path)

            try:
                addr = query["addr"][0]
                getPages.unsubscribe(addr)
            except:
                pass

            self.wfile.write(getPages.subscriptions())

        elif self.path.startswith("/subscribe"):
            query = parseQuery(self.path)

            try:
                addr = query["addr"][0]
                label = query["label"][0]
                getPages.subscribe(addr, label)
            except:
                pass

            self.wfile.write(getPages.subscriptions())

        elif self.path.startswith("/addressbook"):
            self.wfile.write(getPages.addressBook())

        elif self.path.startswith("/addaddress"):
            query = parseQuery(self.path)

            try:
                addr = query["addr"][0]
                label = query["label"][0]
                getPages.addAddressBookEntry(addr, label)
            except:
                pass

            self.wfile.write(getPages.addressBook())

        elif self.path.startswith("/deladdress"):
            query = parseQuery(self.path)

            try:
                addr = query["addr"][0]
                getPages.delAddressBookEntry(addr)
            except:
                pass

            self.wfile.write(getPages.addressBook())

        elif self.path.startswith("/markread"):
            query = parseQuery(self.path)

            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.markRead(msgid)

        elif self.path.startswith("/markunread"):
            query = parseQuery(self.path)

            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.markUnread(msgid)

        elif self.path.startswith("/delmsg"):
            query = parseQuery(self.path)

            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.delMsg(msgid)

        elif self.path.startswith("/delsentmsg"):
            query = parseQuery(self.path)

            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.delSentMsg(msgid)

        else:
            html = HTMLPage()
            html.addLine("<h1>404 - Not found</h1>")
            self.wfile.write(html.getPage())
Ejemplo n.º 4
0
def connectionStatus():
    """Returns page with connection Status"""

    try:
        page = HTMLPage()
        page.addLine(u"<h1>Connection status</h1>", False)

        try:
            status = json.loads(api.clientStatus())
                
            page.addLine(u"<center><table border=1>", False)
            page.addLine(u"<tr><th>Network status</th><td>"+getNetworkStatusString(status['networkStatus'])+"</td></tr>", False)
            page.addLine(u"<tr><th>Number of connections</th><td>"+str(status['networkConnections'])+"</td></tr>", False)
            page.addLine(u"<tr><th>Number of messages processed</th><td>"+str(status['numberOfMessagesProcessed'])+"</td></tr>", False)
            page.addLine(u"<tr><th>Number of broadcasts processed</th><td>"+str(status['numberOfBroadcastsProcessed'])+"</td></tr>", False)
            page.addLine(u"<tr><th>Number of pubkeys processed</th><td>"+str(status['numberOfPubkeysProcessed'])+"</td></tr>", False)
            page.addLine(u"<tr><th>Software</th><td>"+status['softwareName']+"</td></tr>", False)
            page.addLine(u"<tr><th>Software Version</th><td>"+status['softwareVersion']+"</td></tr>", False)
            page.addLine(u"</table></center>", False) 
        except:
            isInit = False
            return connectionErrorPage()

    except:
        page = connectionErrorPage()
        apiIsInit = False

    return page.getPage()
Ejemplo n.º 5
0
def identities():
    """Returns page with identities or error page."""

    page = HTMLPage()

    page.addLine(u"<h1>Your Identities</h1>", False)

    #Form to add random address
    page.addLine(u"<form action='addrandomaddress' method='post' enctype='multipart/form-data'>", False)
    page.addLine(u"New random address: ", False)
    page.addLine(u"<input type='text' name='label' placeholder='Label' />", False)
    page.addLine(u"<input type='submit' value='Generate' class='button' />", False)
    page.addLine(u"</form>")

    #Show all addresses
    try:
        addresses = json.loads(api.listAddresses2())
    except:
        isInit = False
        return connectionErrorPage()
    
    for addr in addresses['addresses']:
        if (addr['chan']):
            continue
        label = sanitize(addr['label'].decode('base64').decode('utf-8'))
        address = addr['address']
        page.addLine(u"<div class='addrbookentry'>", False)
        if (addr['enabled']):
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
        else:
            page.addLine(label + u" (Disabled)")
        page.addLine(address)
        page.addLine(u"(Stream %s)" % (str(addr['stream'])))

        #Hidden form to delete address
        page.addLine(u"<form id='%s' action='deladdress' method='post' enctype='multipart/form-data'>" % (address), False)
        page.addLine(u"<input name='addr' value='%s' type='hidden'>" % (address), False)
        page.addLine(u"</form>", False)

        page.addLine(u"<a onclick='sendForm(\"%s\", \"Remove %s permanently?\")'>Delete</a>" % (address, label), False)
        page.addLine(u"</div>")

    return page.getPage()
Ejemplo n.º 6
0
def chans():
    """Returns page with chans or error page."""

    page = HTMLPage()

    page.addLine(u"<h1>Chans</h1>", False)

    #Form to join chan
    page.addLine(u"<form action='joinchan' method='post' enctype='multipart/form-data'>", False)
    page.addLine(u"<input type='text' name='pw' placeholder='Passphrase' />", False)
    page.addLine(u"<input type='text' name='addr' placeholder='Address' />", False)
    page.addLine(u"<input type='submit' value='Join' class='button' />", False)
    page.addLine(u"</form>")

    #Form to create chan
    page.addLine(u"<form action='createchan' method='post' enctype='multipart/form-data'>", False)
    page.addLine(u"<input type='text' name='pw' placeholder='Passphrase' />", False)
    page.addLine(u"<input type='submit' value='Create' class='button' />", False)
    page.addLine(u"</form>")

    #Show all chans
    try:
        addresses = json.loads(api.listAddresses2())
    except:
        isInit = False
        return connectionErrorPage()
    
    for addr in addresses['addresses']:
        if (not addr['chan']):
            continue
        label = sanitize(addr['label'].decode('base64').decode('utf-8'))
        if label.startswith("[chan] "):
            label = label[7:]
        address = addr['address']
        page.addLine(u"<div class='addrbookentry'>", False)
        if (addr['enabled']):
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
        else:
            page.addLine(label + u" (Disabled)")
        page.addLine(address)

        #Hidden form to leave chan
        page.addLine(u"<form id='%s' action='leavechan' method='post' enctype='multipart/form-data'>" % (address), False)
        page.addLine(u"<input name='addr' value='%s' type='hidden'>" % (address), False)
        page.addLine(u"</form>", False)

        page.addLine(u"<a onclick='sendForm(\"%s\", \"Leave chan %s?\")'>Leave</a>" % (address, label), False)
        page.addLine(u"</div>")

    return page.getPage()
Ejemplo n.º 7
0
def addressBook():
    """Returns page with address book or error page"""

    try:
        page = HTMLPage()
        page.addLine(u"<h1>Address book</h1>", False)

        #Form to add address
        page.addLine(u"<form action='addaddressbookentry' method='post' enctype='multipart/form-data'>", False)
        page.addLine(u"<input type='text' name='addr' id='focus' placeholder='Address' />", False)
        page.addLine(u"<input type='text' name='label' placeholder='Label' />", False)
        page.addLine(u"<input type='submit' value='Add' class='button' />", False)
        page.addLine(u"</form>")

        #List all addresses
        response = api.listAddressBookEntries()
        addressBook = json.loads(response)
        for entry in addressBook['addresses']:
            label = sanitize(entry['label'].decode('base64').decode('utf-8'))
            address = entry['address']
            page.addLine(u"<div class='addrbookentry'>", False)
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
            page.addLine(address)

            #Hidden form for delete addressbook entry
            page.addLine(u"<form id='del-%s' action='deladdressbookentry' method='post' enctype='multipart/form-data'>" % (address), False)
            page.addLine(u"<input name='addr' value='%s' type='hidden'>" % (address), False)
            page.addLine(u"</form>", False)

            #Hidden form to write message
            page.addLine(u"<form id='msg-%s' action='composer' method='post' enctype='multipart/form-data'>" % (address), False)
            page.addLine(u"<input name='to' value='%s' type='hidden'>" % (address), False)
            page.addLine(u"</form>", False)

            #Add buttons
            page.addLine(u"<a onclick='sendForm(\"msg-%s\")'>Write message</a>" % (address), False)
            page.addLine(u"<a onclick='sendForm(\"del-%s\", \"Delete %s from addressbook?\")'>Delete</a>" % (address, label), False)
            page.addLine(u"</div>")


    except:
        page = connectionErrorPage()
        apiIsInit = False

    return page.getPage()
Ejemplo n.º 8
0
def subscriptions():
    """Returns path with subscriptions or error page."""

    page = HTMLPage()

    try:
        respons = api.listSubscriptions()
        subscriptions = json.loads(respons)
    except:
        isInit = False
        return connectionErrorPage()

    page.addLine(u"<h1>Subscriptions</h1>", False)

    #Form to subscribe to address
    page.addLine(u"<form action='subscribe' methode='get'>", False)
    page.addLine(u"<input type='text' name='addr' id='focus' placeholder='Address' />", False)
    page.addLine(u"<input type='text' name='label' placeholder='Label' />", False)
    page.addLine(u"<input type='submit' value='Subscribe' class='button' />", False)
    page.addLine(u"</form>")

    #List all subscriptions
    for sub in subscriptions['subscriptions']:
        label = sanitize(sub['label'].decode('base64').decode('utf-8'))
        page.addLine(u"<div class='subscription'>", False)
        if (sub['enabled']):
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
        else:
            page.addLine(label + u" (Disabled)")
        page.addLine(sub['address'])

        page.addLine(u"<a href='unsubscribe?addr=%s'>Unsubscribe</a>" % (sub['address']), False)
        page.addLine(u"</div>")
                  
    return page.getPage()
Ejemplo n.º 9
0
def subscriptions():
    """Returns path with subscriptions or error page."""

    page = HTMLPage()

    try:
        respons = api.listSubscriptions()
        subscriptions = json.loads(respons)
    except:
        isInit = False
        return connectionErrorPage()

    page.addLine(u"<h1>Subscriptions</h1>", False)

    #Form to subscribe to address
    page.addLine(u"<form action='subscribe' method='post' enctype='multipart/form-data'>", False)
    page.addLine(u"<input type='text' name='addr' id='focus' placeholder='Address' />", False)
    page.addLine(u"<input type='text' name='label' placeholder='Label' />", False)
    page.addLine(u"<input type='submit' value='Subscribe' class='button' />", False)
    page.addLine(u"</form>")

    #List all subscriptions
    for sub in subscriptions['subscriptions']:
        label = sanitize(sub['label'].decode('base64').decode('utf-8'))
        page.addLine(u"<div class='subscription'>", False)
        if (sub['enabled']):
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
        else:
            page.addLine(label + u" (Disabled)")
        page.addLine(sub['address'])

        #Hidden form for unsubscribe
        page.addLine(u"<form id='%s' action='unsubscribe' method='post' enctype='multipart/form-data'>" % (sub['address']), False)
        page.addLine(u"<input name='addr' value='%s' type='hidden'>" % (sub['address']), False)
        page.addLine(u"</form>", False)

        page.addLine(u"<a onclick='sendForm(\"%s\", \"Unsubscribe from %s?\")'>Unsubscribe</a>" % (sub['address'], label), False)
        page.addLine(u"</div>")
                  
    return page.getPage()
Ejemplo n.º 10
0
def outbox():
    """Returns page with outbox or error page."""

    #Clear image cache
    global images
    images = dict()

    page = HTMLPage()
    page.addLine(u"<h1>Outbox</h1>", False)

    try:
        outboxMessages = json.loads(api.getAllSentMessages())
    except:
        apiIsInit = False
        return connectionErrorPage()

    fallbackId = 0

    messages = outboxMessages['sentMessages']
    messages.reverse() #Revers order to show newest messages on top.
    for message in messages: 
        msgId = message['msgid']
        if msgId == '': #Unsend messages have no id
            msgId = u"fallback_" + str(fallbackId)
            fallbackId += 1
        page.addLine(u"<div class='msgHeaderRead' id='H-%s' onclick='ShowHideDiv(\"%s\")'>" % (msgId, msgId), False)
        page.addLine(u"To: " + getLabelForAddress(message['toAddress'])) 
        page.addLine(u"Subject: " + processText(message['subject'])) 
        page.addLine(u"</div><div class='msgBody' id='%s'>" % (msgId), False)
        page.addLine(u"From: " + getLabelForAddress(message['fromAddress']))
        page.addLine(u"Status: " + message['status']) 
        page.addLine(u"Send: " + datetime.datetime.fromtimestamp(float(message['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'))
        page.addLine(u"<div class='msgText'>", False)
        page.addLine(processText(message['message'], msgId))
        page.addLine(u"</div>")
        page.addLine(u"<a onclick='delSentMsg(\"%s\")'>Delete</a>" % (msgId))
        page.addLine(u"</div>")

    return page.getPage()
Ejemplo n.º 11
0
def inbox(): 
    """Returns inbox or error page."""

    #Clear image cache
    global images
    images = dict()

    page = HTMLPage()
    page.addLine(u"<h1>Inbox</h1>", False)

    try:
        inboxMessages = json.loads(api.getAllInboxMessages())
    except:
        apiIsInit = False
        return connectionErrorPage()

    messages = inboxMessages['inboxMessages']
    messages.reverse() #Revers order to show newest meesage on top
    for message in messages: 
        msgId = message['msgid']
        if message['read']:
            page.addLine(u"<div class='msgHeaderRead' id='H-%s' onclick='ShowHideDiv(\"%s\")'>" % (msgId, msgId), False)
        else:
            page.addLine(u"<div class='msgHeaderUnread' id='H-%s' onclick='ShowHideDiv(\"%s\")'>" % (msgId, msgId), False)
        page.addLine(u"From: " + getLabelForAddress(message['fromAddress']))
        page.addLine(u"Subject: " + processText(message['subject'])) 
        page.addLine(u"</div><div class='msgBody' id='%s'>" % (msgId), False)
        page.addLine(u"To: " + getLabelForAddress(message['toAddress'])) 
        page.addLine(u"Received: " + datetime.datetime.fromtimestamp(float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'))
        page.addLine(u"<div class='msgText'>", False)
        page.addLine(processText(message['message'], msgId))
        page.addLine(u"</div>")

        #Prepare text for reply and add it to the link
        to = message['fromAddress']

        subject = message['subject'].decode('base64').decode('utf-8')
        if not subject.startswith(u"Re:"):
            subject = u"Re: " + subject
        subject = subject.encode('utf-8').encode('base64')

        text = message['message'].decode('base64').decode('utf-8')
        text = u"\n\n------------------------------------------------------\n" + text
        text = text.encode('utf-8').encode('base64')

        #Hidden form for reply
        page.addLine(u"<form id='%s' action='composer' method='post' enctype='multipart/form-data'>" % (msgId), False)
        page.addLine(u"<input name='replyto' value='%s' type='hidden'>" % (msgId), False)
        page.addLine(u"</form>", False)

        #Add buttons 
        page.addLine(u"<a onclick='sendForm(\"%s\")'>Reply</a>" % (msgId), False)
        page.addLine(u"<a onclick='markUnread(\"%s\")'>Unread</a>" % (msgId), False)
        page.addLine(u"<a onclick='delMsg(\"%s\")'>Delete</a>" % (msgId))
        page.addLine(u"</div>")

    return page.getPage()
Ejemplo n.º 12
0
def sendMsg(toAddress, fromAddress, subject, message, broadcast=False): 
    """Sends message and return status page.
    All parameters must be unencoded!"""
    
    page = HTMLPage()
    error = False

    if not validAddress(toAddress) and not broadcast:
        page.addLine(u"<h1>Receivers address not valid!</h1>", False)
        error = True
        
    if not validAddress(fromAddress):
        page.addLine(u"<h1>Senders address not valid!</h1>", False)
        error = True

    subject = subject.encode('base64')
    message = message.encode('base64')

    if error:
        return page.getPage()
            
    try:
        if broadcast:
            api.sendBroadcast(fromAddress, subject, message)
        else:
            api.sendMessage(toAddress, fromAddress, subject, message)
        page.addLine(u"<h1>Message send!</h1>", False)
        page.addLine(u"For status see outbox.")
    except:
        apiIsInit = False
        return connectionErrorPage()

    return page.getPage()
Ejemplo n.º 13
0
def addressBook():
    """Returns page with address book or error page"""

    try:
        page = HTMLPage()
        page.addLine(u"<h1>Address book</h1>", False)

        #Form to add address
        page.addLine(u"<form action='addaddress' methode='get'>", False)
        page.addLine(u"<input type='text' name='addr' id='focus' placeholder='Address' />", False)
        page.addLine(u"<input type='text' name='label' placeholder='Label' />", False)
        page.addLine(u"<input type='submit' value='Add' class='button' />", False)
        page.addLine(u"</form>")

        #List all addresses
        response = api.listAddressBookEntries()
        addressBook = json.loads(response)
        for entry in addressBook['addresses']:
            label = sanitize(entry['label'].decode('base64').decode('utf-8'))
            address = entry['address']
            page.addLine(u"<div class='addrbookentry'>", False)
            page.addLine(u"<div class='label'>%s</div>" % (label), False)
            page.addLine(address)
            page.addLine(u"<a href='composer?to=%s'>Write message</a>" % (address), False)
            page.addLine(u"<a href='deladdress?addr=%s'>Delete</a>" % (address), False)
            page.addLine(u"</div>")


    except:
        page = connectionErrorPage()
        apiIsInit = False

    return page.getPage()
Ejemplo n.º 14
0
def composeMsg(to = "", subject = "", text = ""):
    """Returns page to compose message or error page.
    Optionally takes to, subject or text.
    Subject and text must be base64 encoded."""

    page = HTMLPage()

    if (subject != ""):
        subject = subject.decode('base64').decode('utf-8')
    if (text != ""):
        text = text.decode('base64').decode('utf-8')

    page.addLine(u"<h1>Composer</h1>", False)
    page.addLine(u"<form action='sendmsg' method='get'>", False)
    page.addLine(u"<input type='text' size='40' name='to' placeholder='To' value='%s' />" % (to))

    #Get own address to chose sender
    page.addLine(u"From: <select name='from' size='1'>", False)

    try:
        response = api.listAddresses2()
        addresses = json.loads(response)
        for entry in addresses['addresses']:
            opt = u"<option value='%s'>%s</option>" % (entry['address'], entry['label'].decode('base64').decode('utf-8'))
            page.addLine(opt, False)
    except:
        apiIsInit = False
        return connectionErrorPage()

    page.addLine(u"</select>")

    page.addLine(u"<input type='text' size='40' name='subject' placeholder='Subject' value='%s' />" % (subject))
    page.addLine(u"<textarea name='text' id='focus' rows='25' cols='50' placeholder='Your message...'>%s</textarea>" % (text))
    page.addLine(u"<input type='submit' class='button' name='send' value='Send message' />")
    page.addLine(u"</form>")

    return page.getPage()
Ejemplo n.º 15
0
    def do_POST(self):
        global sessionID
        self.headerFinished = False
        self.send_response(200)

        #Parse query
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                query = cgi.parse_multipart(self.rfile, pdict)
            else:
                query = None
        except:
            query = None

        #Session Management
        authenticated = False

        #Check password
        if self.path.startswith("/pwd"):
            try:
                pwd = query.get("pwd")[0]
            except:
                pwd = None

            if password.isCorrect(pwd):
                sessionID = urandom(16).encode('base64').strip()
                self.send_header("Set-Cookie", "bitweb_sessionID=\"" + sessionID + "\"; Max-Age=2592000; Version=\"1\"; Secure; Port; HttpOnly")
                authenticated = True
                #Redirect to inbox
                self.path = "/inbox"
                sleep(1) #To slow down brutforce
            else:
                self.send_header('Content-type', 'text/html')
                self.write(password.enterHTML(True))
                sleep(1) #To slow down brutforce
                return

        #Set password
        if self.path.startswith("/setpwd") and not password.isSet():
            try:
                pwd = query["pwd"][0]
                password.set(pwd)
                authenticated = True
            except:
                authenticated = False

        #Check Authentication
        if (not authenticated) and (not self.isAuthenticated()) :
            return

        #End of session management. 
        #The following code should only be executed when the user has passed authentication!

        #Check api
        if not self.initApi():
            return

        #Header for text
        self.send_header('Content-type', 'text/html')
                
        #Handel called URL
        if self.path.startswith("/inbox") or self.path == "/":
            self.write(getPages.inbox())

        elif self.path.startswith("/composer"):
            toAddress = False
            replyTo = False
            try:
                if query.has_key("to"):
                    toAddress = query["to"][0]
                if query.has_key("replyto"):
                    replyTo = query["replyto"][0]
            except:
                pass
                
            self.write(getPages.composeMsg(replyTo, toAddress))

        elif self.path.startswith("/sendmsg"):
            try:
                if query.has_key("to"):
                    toAddress = query["to"][0]
                else:
                    #There is no reciever for broadcast messages
                    toAddress = ""
                fromAddress = query["from"][0]
                subject = query["subject"][0]
                text = query["text"][0]
                if query["broadcast"][0] == "true":
                    broadcast = True
                else:
                    broadcast = False
            except:
                page = HTMLPage()
                page.addLine("<h1>Error while parsing message.")
                page.addLine("Message NOT send!</h1>")
                self.write(page.getPage())
                return

            self.write(getPages.sendMsg(toAddress, fromAddress, subject, text, broadcast))

        elif self.path.startswith("/unsubscribe"):
            try:
                addr = query["addr"][0]
                getPages.unsubscribe(addr)
            except:
                pass

            self.write(getPages.subscriptions())

        elif self.path.startswith("/subscribe"):
            try:
                addr = query["addr"][0]
                label = query["label"][0]
                getPages.subscribe(addr, label)
            except:
                pass

            self.write(getPages.subscriptions())

        elif self.path.startswith("/addaddressbookentry"):
            try:
                addr = query["addr"][0]
                label = query["label"][0]
                getPages.addAddressBookEntry(addr, label)
            except:
                pass

            self.write(getPages.addressBook())

        elif self.path.startswith("/deladdressbookentry"):
            try:
                addr = query["addr"][0]
                getPages.delAddressBookEntry(addr)
            except:
                pass

            self.write(getPages.addressBook())

        elif self.path.startswith("/createchan"):
            try:
                pw = query["pw"][0]
                getPages.createChan(pw)
            except:
                pass
            
            self.write(getPages.chans())

        elif self.path.startswith("/joinchan"):
            try:
                pw = query["pw"][0]
                addr = query["addr"][0]
                getPages.joinChan(pw, addr)
            except:
                pass
            
            self.write(getPages.chans())

        elif self.path.startswith("/leavechan"):
            try:
                addr = query["addr"][0]
                getPages.leaveChan(addr)
            except:
                pass
            
            self.write(getPages.chans())

        elif self.path.startswith("/addrandomaddress"):
            try:
                label = query["label"][0]
                getPages.genRandomAddress(label)
            except:
                pass

            self.write(getPages.identities())

        elif self.path.startswith("/deladdress"):
            try:
                addr = query["addr"][0]
                getPages.delAddress(addr)
            except:
                pass

            self.write(getPages.identities())

        else:
            html = HTMLPage()
            html.addLine("<h1>Page not found!</h1>", False)
            self.write(html.getPage())
Ejemplo n.º 16
0
def composeMsg(replyTo = False, toAddress = False):
    """Returns page to compose message or error page.
    Optionally takes to, subject or text.
    Subject and text must be base64 encoded."""

    page = HTMLPage()

    if replyTo:
        message = getMessageById(replyTo)
        if message:
            toAddress = message['fromAddress']

            subject = message['subject'].decode('base64').decode('utf-8')
            if not subject.startswith(u"Re:"):
                subject = u"Re: " + subject

            text = message['message'].decode('base64').decode('utf-8')
            text = u"\n\n------------------------------------------------------\n" + text
        else:
            toAddress = u""
            subject = u""
            text = u""
    else:
        if not toAddress:
            toAddress = u""
        subject = u""
        text = u""

    page.addLine(u"<h1>Composer</h1>", False)
    page.addLine(u"<form action='sendmsg' method='post' enctype='multipart/form-data'>", False)

    #Add radio buttons to select direct message or broadcast
    page.addLine(u"<input type='radio' name='broadcast' value='false' onclick='broadcastMsg(false)' checked />", False)
    page.addLine(u"Send direct message")
    page.addLine(u"<input type='radio' name='broadcast' value='true' onclick='broadcastMsg(true)' />", False)
    page.addLine(u"Send broadcast message")

    #To
    page.addLine(u"<input type='text' size='40' name='to' id='to' placeholder='To' value='%s' />" % (toAddress))

    #Get own address to chose sender
    page.addLine(u"From: <select name='from' size='1'>", False)

    try:
        response = api.listAddresses2()
        addresses = json.loads(response)
        for entry in addresses['addresses']:
            opt = u"<option value='%s'>%s</option>" % (entry['address'], entry['label'].decode('base64').decode('utf-8'))
            page.addLine(opt, False)
    except:
        apiIsInit = False
        return connectionErrorPage()

    page.addLine(u"</select>")

    #Subject and message
    page.addLine(u"<input type='text' size='40' name='subject' placeholder='Subject' value='%s' />" % (subject))
    page.addLine(u"<textarea name='text' id='focus' rows='25' cols='50' placeholder='Your message...'>%s</textarea>" % (text))
    page.addLine(u"<input type='submit' class='button' name='send' value='Send message' />")
    page.addLine(u"</form>")

    return page.getPage()
Ejemplo n.º 17
0
    def do_GET(self):
        global sessionID
        self.headerFinished = False
        self.send_response(200)

        #return favicon.ico
        if self.path.startswith("/favicon.ico"):
            self.send_header('Content-type', 'image/x-icon')

            try: 
                f = open("favicon.ico", "rb")
                self.write(f.read())
            except:
                pass
            return

        #Parse query
        if '?' in self.path:
            qs = self.path[self.path.find('?')+1:]
            query = cgi.parse_qs(qs, keep_blank_values = True)
        else:
            query = None

        #Check Authentication
        if not self.isAuthenticated():
            return

        #The following code should only be executed when the user has passed authentication!

        #Check api
        if not self.initApi():
            return
                
        #Handel called URL

        #Return requested image
        if self.path.startswith("/getimage"):
            params = self.path.split("-")
            imageHash = params[1].split(".")[0]
            
            ret = getPages.getImage(imageHash)
            if not ret:
                return

            mimeType, image = ret
            
            self.send_header('Content-type', mimeType)
            self.write(image)
            return
        else:
            #Header for text
            self.send_header('Content-type', 'text/html')

        #Return requestet page
        if self.path.startswith("/inbox") or self.path == "/":
            self.write(getPages.inbox())

        elif self.path.startswith("/outbox"):
            self.write(getPages.outbox())

        elif self.path.startswith("/composer"):
            self.write(getPages.composeMsg())

        elif self.path.startswith("/subscriptions"):
            self.write(getPages.subscriptions())

        elif self.path.startswith("/addressbook"):
            self.write(getPages.addressBook())

        elif self.path.startswith("/chans"):
            self.write(getPages.chans())

        elif self.path.startswith("/identities"):
            self.write(getPages.identities())

        elif self.path.startswith("/status"):
            self.write(getPages.connectionStatus())

        elif self.path.startswith("/logout"):
            sessionID = None
            self.write(password.enterHTML())

        elif self.path.startswith("/markread"):
            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.markRead(msgid)

        elif self.path.startswith("/markunread"):
            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.markUnread(msgid)

        elif self.path.startswith("/delmsg"):
            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.delMsg(msgid)

        elif self.path.startswith("/delsentmsg"):
            try:
                msgid = query["msgid"][0]
            except:
                return

            getPages.delSentMsg(msgid)

        else:
            html = HTMLPage()
            html.addLine("<h1>Page not found!</h1>", False)
            self.write(html.getPage())
Ejemplo n.º 18
0
def apiData():
    """Try to load api data from PyBittmessages keys.dat
    Returns tulple of [errorPage, apiData] where on of it is False."""

    keysPath = 'keys.dat'
    
    config = ConfigParser.SafeConfigParser()    
    config.read(keysPath) #First try to load the config file (the keys.dat file) from the program directory

    try:
        config.get('bitmessagesettings','port')
        appDataFolder = ''
    except:
        #Could not load the keys.dat file in the program directory. Perhaps it is in the appdata directory.
        appDataFolder = lookupAppdataFolder()
        keysPath = appDataFolder + keysPath
        config = ConfigParser.SafeConfigParser()
        config.read(keysPath)

        try:
            config.get('bitmessagesettings','port')
        except:
            page = HTMLPage()
            page.addLine(u"<h1>Error</h1>", False)
            page.addLine(u"Can't find keys.dat!")

            return [page.getPage(), False]

    #try: #Try to load settings from keys.dat 
    apiEnabled = config.getboolean('bitmessagesettings', 'apienabled')
    apiPort = int(config.get('bitmessagesettings', 'apiport'))
    apiInterface = config.get('bitmessagesettings', 'apiinterface')
    apiUsername = config.get('bitmessagesettings', 'apiusername')
    apiPassword = config.get('bitmessagesettings', 'apipassword')
    #except:
    #    apiEnabled = False

    if apiEnabled:    
        return [False, "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface+ ":" + str(apiPort) + "/"] #Build the api credentials
    else:
        page = HTMLPage()
        page.addLine(u"<h1>Error</h1>")
        page.addLine(u"PyBittmessage api not configured correctly in keys.dat!")
        return [page.getPage(), False]
Ejemplo n.º 19
0
def enterHTML(wrongPassword = False):
    page = HTMLPage()

    page.addLine("<h1>Login</h1>", False)
    if wrongPassword:
        page.addLine("Password not correct!")
    page.addLine("<form action='pwd' method='get'>", False)
    page.addLine("<input type='password' name='pwd' id='focus' />")
    page.addLine("<input type='submit' class='button' value='Login' />", False)

    return page.getPage()
Ejemplo n.º 20
0
def inbox(): 
    """Returns inbox or error page."""

    page = HTMLPage()
    page.addLine(u"<h1>Inbox</h1>", False)

    try:
        inboxMessages = json.loads(api.getAllInboxMessages())
    except:
        apiIsInit = False
        return connectionErrorPage()

    messages = inboxMessages['inboxMessages']
    messages.reverse() #Revers order to show newest meesage on top
    for message in messages: 
        msgId = message['msgid']
        if message['read']:
            page.addLine(u"<div class='msgHeaderRead' id='H-%s' onclick='ShowHideDiv(\"%s\")'>" % (msgId, msgId), False)
        else:
            page.addLine(u"<div class='msgHeaderUnread' id='H-%s' onclick='ShowHideDiv(\"%s\")'>" % (msgId, msgId), False)
        page.addLine(u"From: " + getLabelForAddress(message['fromAddress']))
        page.addLine(u"Subject: " + processText(message['subject'])) 
        page.addLine(u"</div><div class='msgBody' id='%s'>" % (msgId), False)
        page.addLine(u"To: " + getLabelForAddress(message['toAddress'])) 
        page.addLine(u"Received: " + datetime.datetime.fromtimestamp(float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'))
        page.addLine(u"<div class='msgText'>", False)
        page.addLine(processText(message['message']))
        page.addLine(u"</div>")

        #Prepare text for reply and add it to the link
        to = message['fromAddress']

        subject = message['subject'].decode('base64').decode('utf-8')
        if not subject.startswith(u"Re:"):
            subject = u"Re: " + subject
        subject = subject.encode('utf-8').encode('base64')

        text = message['message'].decode('base64').decode('utf-8')
        text = u"\n\n------------------------------------------------------\n" + text
        text = text.encode('utf-8').encode('base64')

        page.addLine(u"<a href='composer?to=%s&subject=%s&text=%s'>Reply</a>" % (to, subject, text), False)
        
        #Add buttons to switch read status
        page.addLine(u"<a onclick='markUnread(\"%s\")'>Unread</a>" % (msgId), False)
        page.addLine(u"<a onclick='delMsg(\"%s\")'>Delete</a>" % (msgId))
        page.addLine(u"</div>")

    return page.getPage()