~deejay1/groundcontrol/fix-for-517605

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#
# Copyright 2009, Martin Owens.
#
# This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>
#
"""
Fake launchpad web browser for logging on and oauthorising and submitting
Things not available via the offical launchpad API.

Hopefully this can be removed when launchpad intergrates better.
"""

import os
import re
import logging
import urllib
import httplib2

from htmllib import HTMLParser
from formatter import NullFormatter
from socket import gethostname

from GroundControl.base import LAUNCHPAD_XDG
from GroundControl.sshkeys import generate_key, generate_key_file


CACHE_DIR = LAUNCHPAD_XDG.get_cache_dir('website')
NORMAL_ROOT = 'https://launchpad.net/'

USER_REX = re.compile('href="\/~(?P<user>.*?)" ' +
    'class="sprite person">(?P<name>.*?)<\/a>')
SSH_REX  = re.compile('input type="hidden" name="key" ' +
    'value="(?P<id>\d*?)".*?<dd style="overflow: auto;">(?P<key>.*?)<',
    re.MULTILINE|re.DOTALL)

class NotLogedInError(KeyError):
    """What happens when your not logged in."""
    pass

class NoUsernameError(ValueError):
    """What happens when we don't have a valid username."""
    pass

class LoginFailedError(ValueError):
    """What happens when the web login fails."""
    pass

class KeyExistsError(ValueError):
    """What happens when there already is a launchpad ssh key uploaded."""
    pass

class GenerateError(ValueError):
    """A problem involving the generation of ssh keys."""
    pass

class PublicMissingError(ValueError):
    """The public half of an SSH key is missing from the local computer."""
    pass


class LaunchpadWeb(object):
    """Fake Launchpad Web Browser"""
    login_file = os.path.join(CACHE_DIR, "auth_login")
    session_file = os.path.join(CACHE_DIR, "session_login")

    def __init__(self, emailaddr=None, password=None, root=NORMAL_ROOT):
        self.address = root
        self.session = None
        self.emailaddr = None
        self.user = None
        self.name = None

        self.get_session()
        if not emailaddr:
            self.get_emailaddr()
        else:
            self.set_emailaddr(emailaddr)

        self.sessions = {}
        self.http = httplib2.Http()
        if self.emailaddr and password:
            self.login(password)

    def logoff(self):
        """Remove the session cookies and email file, reset object"""
        logging.debug("Removing WebLogin File")
        os.unlink(self.login_file)
        logging.debug("Removing Session File")
        os.unlink(self.session_file)
        self.name      = None
        self.emailaddr = None
        self.user      = None
        self.session   = None
        self.sessions  = {}

    def set_emailaddr(self, emailaddr, write=True):
        """Set the emailaddr to something interesting"""
        logging.debug("Setting emailaddr to '%s'" % emailaddr)
        self.emailaddr = emailaddr
        if write:
            logging.debug("Writing emailaddr to file '%s'" % self.login_file)
            fhl = open(self.login_file, "w")
            fhl.write(self.emailaddr)
            fhl.close()

    def get_emailaddr(self, efile=None):
        """Get the emailaddr from a file"""
        if not efile:
            efile = self.login_file
        if os.path.exists(efile):
            fhl = open(efile, "r")
            logging.debug("Loading emailaddr from '%s'" % efile)
            self.set_emailaddr(fhl.read(), write=False)
            fhl.close()

    def set_session(self, session_key, write=True):
        """Set the session cookie to something interesting"""
        logging.debug("Setting session to '%s' (%s)" % (
            session_key, str(write)))
        self.session = session_key
        if write:
            logging.debug("Writing session to file '%s'" % (
                self.session_file))
            fhl = open(self.session_file, "w")
            fhl.write(self.session)
            fhl.close()

    def get_session(self, file=None):
        """Get the session cookie from a file"""
        if not file:
            file = self.session_file
        if os.path.exists(file):
            fhl = open(file, "r")
            logging.debug("Loading session from '%s'" % file)
            self.set_session(fhl.read(), write=False)
            fhl.close()

    def login(self, password):
        """Log in to Launchpad services"""
        logging.debug("Logging in to launchpad...")
        if not self.emailaddr:
            raise NoUsernameError("Launchpad Email Address not found.")
        # Login to session
        details = {
            'loginpage_password'     : password,
            'loginpage_email'        : self.emailaddr,
            'loginpage_submit_login' : 'Log In',
        }
        try:
            content = self.request('+login',
                method='POST',
                data=details)
            self.store_metadata(content)
        except NotLogedInError:
            raise LoginFailedError("Failed to Login to Launchpad")
        return content

    def store_metadata(self, content):
        """Makes use of standard data about a logged in user"""
        rex = USER_REX.search(content)
        if rex:
            dict = rex.groupdict()
            self.user = dict['user']
            self.name = dict['name']
        else:
            logging.warn(_("Unable to generate data from content."))
            self.user = None
            self.name = None

    def loggedin(self):
        """Return true if the current state is logged in launchpad"""
        try:
            self.store_metadata(self.request(""))
        except NotLogedInError:
            return False
        return True

    def request(self, url, method='GET', data=None, user_required=True):
        """Make a launchpad request"""
        if '://' not in url:
            url = self.address + url

        body = None
        headers = {}

        if self.session:
            headers['Cookie'] = self.session
            logging.debug("Feeding in cookie '%s'" % self.session)
        else:
            logging.debug("No cookie to feed in")

        http = httplib2.Http()
        if method == 'POST' and data:
            body = urllib.urlencode(data)
            headers['Content-type'] = 'application/x-www-form-urlencoded'
            http.follow_redirects = False
        elif method == 'POST':
            method = 'GET'

        headers['User-Agent'] = 'Mozilla/5.0'

        logging.debug("Requesting '%s' via %s headers: '%s' and body: '%s'"
            % (url, method, str(headers), str(body)) )

        response, content = http.request( url, method,
            headers=headers, body=body )

        # Save session cookies here, this doesn't check to see
        # if it's the right cookie, so possible future errors.
        if response.has_key('set-cookie'):
            logging.debug("Got cookie response")
            self.set_session(response['set-cookie'])

        if user_required and (content.find('+login') > 0
            or content.find('form name="login"') > 0):
            raise NotLogedInError("Launchpad web isn't logged in any more.")
        elif user_required:
            logging.debug("User found, your logged in")
        else:
            logging.debug("User wasn't required to be logged in")
        return content

    # EXTRA FUNCTIONS
    def user_request(self, url, method='GET', data=None):
        """Make a user specific request"""
        if not self.user:
            self.loggedin()
        return self.request("~%s/%s" % (self.user, url), method, data)

    def ssh_keys(self):
        """Return a list of stored ssh public keys.

        Note that the keys on Launchpad may be multiple lines so they must be
        joined and have the newlines stripped.
        """
        keys = self.user_request("+sshkeys").split("\n\n")
        return [key.replace('\n', '') for key in keys]

    def ssh_keys_dict(self):
        """Returns a dictionary of ssh keys with lp db ids as keys"""
        content = self.user_request("+editsshkeys")
        result = {}
        for rex in SSH_REX.findall(content):
            result[rex[0]] = rex[1]
        return result

    def add_ssh_key(self, key):
        """Add an SSH key to your launchpad account."""
        return self.user_request("+editsshkeys",
            method="POST",
            data={ 'action': 'add_ssh', 'sshkey': key })

    def del_ssh_key(self, lkey):
        """Remove an SSH key from the lp account."""
        pres = self.ssh_keys_dict()
        for kid, okey in pres.iteritems():
            if okey in lkey:
                logging.debug("Removing Key %s '%s'" % (kid, okey[-20]))
                return self.user_request("+editsshkeys",
                    method="POST",
                    data={ 'action': 'remove_ssh', 'key': kid })
            logging.debug("Key %s doesn't match: '%s' in '%s'" % (
                kid, okey[-10:], lkey[-25:]))
        return None

    def gen_key_filename(self):
        """Return the filename that we use for our ssh key"""
        return generate_key_file('launchpad')

    def has_gen_key(self, filename=None):
        """Returns true if we already have our generated key"""
        if not filename:
            filename = self.gen_key_filename()
        return os.path.exists(filename)

    def gen_ssh_key(self, passwd):
        """Generate a new ssh key and upload to launchpad."""
        # This should make a specific key just for launchpad for no conflict.
        logging.debug("Generating new Ssh Key for launchpad.")
        filename = self.gen_key_filename()
        if self.has_gen_key(filename):
            raise KeyExistsError("LP SSH Key already exists, wont regenerate.")

        # The comment will identify the ssh key as generated for launchpad.
        username = os.environ.get("USER")
        cmnt = "%s@launchpad.%s" % (username, str(gethostname()))
        logging.debug("Key doesn't exist, creating: %s" % cmnt)

        if not generate_key(filename, passwd, comment=cmnt):
            raise GenerateError("Could not generate launchpad key.")
        return self.upload_key(filename)

    def upload_key(self, filename=None):
        """Uploads a key to the server spcified by filesname"""
        if not filename:
            filename = self.gen_key_filename()
        if not ".pub" in filename:
            filename += ".pub"
        if os.path.exists(filename):
            logging.debug("Uploading %s to launchpad." % filename)
            fhl = open(filename, "r")
            self.add_ssh_key(fhl.readline())
            fhl.close()
            logging.debug("Finished Key Re-Uploaded...")
            return True
        raise PublicMissingError("Public bit of sshKey Missing: %s" % filename)


METHODS = {
  'submit' : 'GET',
  'post'   : 'POST',
}

class Form(object):
    """Parse a simple form"""
    def __init__(self, action=None, method=None, **attrs):
        self.inputs = {}
        self.submit = {}
        self.action = action
        self.attrs  = attrs
        self.method = METHODS[method.lower()]

    def add_input(self, name=None, value=None, **attrs):
        """Add an input to the form object."""
        atype = attrs.pop('type')
        if atype == 'submit':
            self.submit[name] = value
        else:
            self.inputs[name] = value

    def submit_data(self, name):
        """Submit data via this form it's self."""
        result = self.inputs.copy()
        if not self.submit.has_key(name):
            logging.error("Can't find submit button: %s from (%s)" % (
                name, ','.join(self.submit.keys())))
        else:
            result[name] = self.submit[name]
        return result


class FormParser(HTMLParser):
    """Parse an HTML form and manage requests."""
    lpmode = None
    def __init__(self, *opts, **attrs):
        HTMLParser.__init__(self, NullFormatter(), *opts, **attrs)
        self.forms = []

    def get_form(self, name):
        """Return the first instance that matches"""
        for pform in self.forms:
            if pform.attrs.has_key('name'):
                if pform.attrs['name'] == name:
                    return pform
        logging.warn("Can't find form %s" % name)

    def proc_fucked_up_attrs(self, attrs):
        """Process wrong headed attributes."""
        result = {}
        for attr in attrs:
            result[attr[0]] = attr[1]
        return result

    def do_form(self, attrs):
        """Form element processing."""
        attr = self.proc_fucked_up_attrs(attrs)
        self.forms.append(Form(**attr))

    def do_input(self, attrs):
        """Input element processing."""
        attr = self.proc_fucked_up_attrs(attrs)
        self.forms[-1].add_input(**attr)