~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugins/launchpad/lp_registration.py

  • Committer: Vincent Ladeuil
  • Date: 2010-10-26 08:08:23 UTC
  • mfrom: (5514.1.1 665100-content-type)
  • mto: This revision was merged to the branch mainline in revision 5516.
  • Revision ID: v.ladeuil+lp@free.fr-20101026080823-3wggo03b7cpn9908
Correctly set the Content-Type header when POSTing http requests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 by Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
7
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
11
 
# # GNU General Public License for more details.
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
18
 
from getpass import getpass
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
19
18
import os
 
19
import socket
20
20
from urlparse import urlsplit, urlunsplit
21
21
import urllib
22
22
import xmlrpclib
23
23
 
24
 
import bzrlib.config
25
 
import bzrlib.errors as errors
 
24
from bzrlib import (
 
25
    config,
 
26
    errors,
 
27
    urlutils,
 
28
    __version__ as _bzrlib_version,
 
29
    )
 
30
from bzrlib.transport.http import _urllib2_wrappers
 
31
 
26
32
 
27
33
# for testing, do
28
34
'''
29
35
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
30
36
'''
31
37
 
 
38
class InvalidLaunchpadInstance(errors.BzrError):
 
39
 
 
40
    _fmt = "%(lp_instance)s is not a valid Launchpad instance."
 
41
 
 
42
    def __init__(self, lp_instance):
 
43
        errors.BzrError.__init__(self, lp_instance=lp_instance)
 
44
 
 
45
 
 
46
class NotLaunchpadBranch(errors.BzrError):
 
47
 
 
48
    _fmt = "%(url)s is not registered on Launchpad."
 
49
 
 
50
    def __init__(self, url):
 
51
        errors.BzrError.__init__(self, url=url)
 
52
 
 
53
 
 
54
class XMLRPCTransport(xmlrpclib.Transport):
 
55
 
 
56
    def __init__(self, scheme):
 
57
        # In python2.4 xmlrpclib.Transport is a old-style class, and does not
 
58
        # define __init__, so we check first
 
59
        init = getattr(xmlrpclib.Transport, '__init__', None)
 
60
        if init is not None:
 
61
            init(self)
 
62
        self._scheme = scheme
 
63
        self._opener = _urllib2_wrappers.Opener()
 
64
        self.verbose = 0
 
65
 
 
66
    def request(self, host, handler, request_body, verbose=0):
 
67
        self.verbose = verbose
 
68
        url = self._scheme + "://" + host + handler
 
69
        request = _urllib2_wrappers.Request("POST", url, request_body)
 
70
        # FIXME: _urllib2_wrappers will override user-agent with its own
 
71
        # request.add_header("User-Agent", self.user_agent)
 
72
        request.add_header("Content-Type", "text/xml")
 
73
 
 
74
        response = self._opener.open(request)
 
75
        if response.code != 200:
 
76
            raise xmlrpclib.ProtocolError(host + handler, response.code,
 
77
                                          response.msg, response.info())
 
78
        return self.parse_response(response)
 
79
 
 
80
 
32
81
class LaunchpadService(object):
33
82
    """A service to talk to Launchpad via XMLRPC.
34
 
    
35
 
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
 
83
 
 
84
    See http://wiki.bazaar.canonical.com/Specs/LaunchpadRpc for the methods we can call.
36
85
    """
37
86
 
38
 
    # NB: this should always end in a slash to avoid xmlrpclib appending
 
87
    LAUNCHPAD_DOMAINS = {
 
88
        'production': 'launchpad.net',
 
89
        'edge': 'edge.launchpad.net',
 
90
        'staging': 'staging.launchpad.net',
 
91
        'demo': 'demo.launchpad.net',
 
92
        'dev': 'launchpad.dev',
 
93
        }
 
94
 
 
95
    # NB: these should always end in a slash to avoid xmlrpclib appending
39
96
    # '/RPC2'
40
 
    DEFAULT_SERVICE_URL = 'https://xmlrpc.launchpad.net/bazaar/'
 
97
    LAUNCHPAD_INSTANCE = {}
 
98
    for instance, domain in LAUNCHPAD_DOMAINS.iteritems():
 
99
        LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
 
100
 
 
101
    # Previously 'edge' was used to avoid a launchpad bug with redirection
 
102
    DEFAULT_INSTANCE = 'production'
 
103
    DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
41
104
 
42
105
    transport = None
43
106
    registrant_email = None
44
107
    registrant_password = None
45
108
 
46
109
 
47
 
    def __init__(self, transport=None):
 
110
    def __init__(self, transport=None, lp_instance=None):
48
111
        """Construct a new service talking to the launchpad rpc server"""
 
112
        self._lp_instance = lp_instance
49
113
        if transport is None:
50
114
            uri_type = urllib.splittype(self.service_url)[0]
51
 
            if uri_type == 'https':
52
 
                transport = xmlrpclib.SafeTransport()
53
 
            else:
54
 
                transport = xmlrpclib.Transport()
 
115
            transport = XMLRPCTransport(uri_type)
55
116
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
56
 
                    % (bzrlib.__version__, xmlrpclib.__version__)
 
117
                    % (_bzrlib_version, xmlrpclib.__version__)
57
118
        self.transport = transport
58
119
 
59
 
 
60
120
    @property
61
121
    def service_url(self):
62
122
        """Return the http or https url for the xmlrpc server.
66
126
        key = 'BZR_LP_XMLRPC_URL'
67
127
        if key in os.environ:
68
128
            return os.environ[key]
 
129
        elif self._lp_instance is not None:
 
130
            try:
 
131
                return self.LAUNCHPAD_INSTANCE[self._lp_instance]
 
132
            except KeyError:
 
133
                raise InvalidLaunchpadInstance(self._lp_instance)
69
134
        else:
70
135
            return self.DEFAULT_SERVICE_URL
71
136
 
72
 
    def get_proxy(self):
 
137
    @classmethod
 
138
    def for_url(cls, url, **kwargs):
 
139
        """Return the Launchpad service corresponding to the given URL."""
 
140
        result = urlsplit(url)
 
141
        lp_instance = result[1]
 
142
        if lp_instance == '':
 
143
            lp_instance = None
 
144
        elif lp_instance not in cls.LAUNCHPAD_INSTANCE:
 
145
            raise errors.InvalidURL(path=url)
 
146
        return cls(lp_instance=lp_instance, **kwargs)
 
147
 
 
148
    def get_proxy(self, authenticated):
73
149
        """Return the proxy for XMLRPC requests."""
74
 
        # auth info must be in url
75
 
        # TODO: if there's no registrant email perhaps we should just connect
76
 
        # anonymously?
77
 
        scheme, hostinfo, path = urlsplit(self.service_url)[:3]
78
 
        assert '@' not in hostinfo
79
 
        assert self.registrant_email is not None
80
 
        assert self.registrant_password is not None
81
 
        # TODO: perhaps fully quote the password to make it very slightly
82
 
        # obscured
83
 
        # TODO: can we perhaps add extra Authorization headers directly to the 
84
 
        # request, rather than putting this into the url?  perhaps a bit more 
85
 
        # secure against accidentally revealing it.  std66 s3.2.1 discourages putting
86
 
        # the password in the url.
87
 
        hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
88
 
                                 urllib.quote(self.registrant_password),
89
 
                                 hostinfo)
90
 
        url = urlunsplit((scheme, hostinfo, path, '', ''))
 
150
        if authenticated:
 
151
            # auth info must be in url
 
152
            # TODO: if there's no registrant email perhaps we should
 
153
            # just connect anonymously?
 
154
            scheme, hostinfo, path = urlsplit(self.service_url)[:3]
 
155
            if '@' in hostinfo:
 
156
                raise AssertionError(hostinfo)
 
157
            if self.registrant_email is None:
 
158
                raise AssertionError()
 
159
            if self.registrant_password is None:
 
160
                raise AssertionError()
 
161
            # TODO: perhaps fully quote the password to make it very slightly
 
162
            # obscured
 
163
            # TODO: can we perhaps add extra Authorization headers
 
164
            # directly to the request, rather than putting this into
 
165
            # the url?  perhaps a bit more secure against accidentally
 
166
            # revealing it.  std66 s3.2.1 discourages putting the
 
167
            # password in the url.
 
168
            hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
 
169
                                     urllib.quote(self.registrant_password),
 
170
                                     hostinfo)
 
171
            url = urlunsplit((scheme, hostinfo, path, '', ''))
 
172
        else:
 
173
            url = self.service_url
91
174
        return xmlrpclib.ServerProxy(url, transport=self.transport)
92
175
 
93
176
    def gather_user_credentials(self):
94
177
        """Get the password from the user."""
95
 
        config = bzrlib.config.GlobalConfig()
96
 
        self.registrant_email = config.user_email()
 
178
        the_config = config.GlobalConfig()
 
179
        self.registrant_email = the_config.user_email()
97
180
        if self.registrant_password is None:
 
181
            auth = config.AuthenticationConfig()
 
182
            scheme, hostinfo = urlsplit(self.service_url)[:2]
98
183
            prompt = 'launchpad.net password for %s: ' % \
99
184
                    self.registrant_email
100
 
            self.registrant_password = getpass(prompt)
 
185
            # We will reuse http[s] credentials if we can, prompt user
 
186
            # otherwise
 
187
            self.registrant_password = auth.get_password(scheme, hostinfo,
 
188
                                                         self.registrant_email,
 
189
                                                         prompt=prompt)
101
190
 
102
 
    def send_request(self, method_name, method_params):
103
 
        proxy = self.get_proxy()
104
 
        assert method_name
 
191
    def send_request(self, method_name, method_params, authenticated):
 
192
        proxy = self.get_proxy(authenticated)
105
193
        method = getattr(proxy, method_name)
106
194
        try:
107
195
            result = method(*method_params)
118
206
                # TODO: print more headers to help in tracking down failures
119
207
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
120
208
                        % (self.service_url, e.errcode, e.errmsg))
 
209
        except socket.gaierror, e:
 
210
            raise errors.ConnectionError(
 
211
                "Could not resolve '%s'" % self.domain,
 
212
                orig_error=e)
121
213
        return result
122
214
 
 
215
    @property
 
216
    def domain(self):
 
217
        if self._lp_instance is None:
 
218
            instance = self.DEFAULT_INSTANCE
 
219
        else:
 
220
            instance = self._lp_instance
 
221
        return self.LAUNCHPAD_DOMAINS[instance]
 
222
 
 
223
    def _guess_branch_path(self, branch_url, _request_factory=None):
 
224
        scheme, hostinfo, path = urlsplit(branch_url)[:3]
 
225
        if _request_factory is None:
 
226
            _request_factory = ResolveLaunchpadPathRequest
 
227
        if scheme == 'lp':
 
228
            resolve = _request_factory(path)
 
229
            try:
 
230
                result = resolve.submit(self)
 
231
            except xmlrpclib.Fault, fault:
 
232
                raise errors.InvalidURL(branch_url, str(fault))
 
233
            branch_url = result['urls'][0]
 
234
            path = urlsplit(branch_url)[2]
 
235
        else:
 
236
            domains = (
 
237
                'bazaar.%s' % domain
 
238
                for domain in self.LAUNCHPAD_DOMAINS.itervalues())
 
239
            if hostinfo not in domains:
 
240
                raise NotLaunchpadBranch(branch_url)
 
241
        return path.lstrip('/')
 
242
 
 
243
    def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
 
244
        """Get the Launchpad web URL for the given branch URL.
 
245
 
 
246
        :raise errors.InvalidURL: if 'branch_url' cannot be identified as a
 
247
            Launchpad branch URL.
 
248
        :return: The URL of the branch on Launchpad.
 
249
        """
 
250
        path = self._guess_branch_path(branch_url, _request_factory)
 
251
        return urlutils.join('https://code.%s' % self.domain, path)
 
252
 
123
253
 
124
254
class BaseRequest(object):
125
255
    """Base request for talking to a XMLRPC server."""
126
256
 
127
257
    # Set this to the XMLRPC method name.
128
258
    _methodname = None
 
259
    _authenticated = True
129
260
 
130
261
    def _request_params(self):
131
262
        """Return the arguments to pass to the method"""
137
268
        :param service: LaunchpadService indicating where to send
138
269
            the request and the authentication credentials.
139
270
        """
140
 
        return service.send_request(self._methodname, self._request_params())
 
271
        return service.send_request(self._methodname, self._request_params(),
 
272
                                    self._authenticated)
141
273
 
142
274
 
143
275
class DryRunLaunchpadService(LaunchpadService):
144
276
    """Service that just absorbs requests without sending to server.
145
 
    
 
277
 
146
278
    The dummy service does not need authentication.
147
279
    """
148
280
 
149
 
    def send_request(self, method_name, method_params):
 
281
    def send_request(self, method_name, method_params, authenticated):
150
282
        pass
151
283
 
152
284
    def gather_user_credentials(self):
165
297
                 author_email='',
166
298
                 product_name='',
167
299
                 ):
168
 
        assert branch_url
 
300
        if not branch_url:
 
301
            raise errors.InvalidURL(branch_url, "You need to specify a non-empty branch URL.")
169
302
        self.branch_url = branch_url
170
303
        if branch_name:
171
304
            self.branch_name = branch_name
199
332
    _methodname = 'link_branch_to_bug'
200
333
 
201
334
    def __init__(self, branch_url, bug_id):
202
 
        assert branch_url
203
335
        self.bug_id = bug_id
204
336
        self.branch_url = branch_url
205
337
 
208
340
        # This must match the parameter tuple expected by Launchpad for this
209
341
        # method
210
342
        return (self.branch_url, self.bug_id, '')
 
343
 
 
344
 
 
345
class ResolveLaunchpadPathRequest(BaseRequest):
 
346
    """Request to resolve the path component of an lp: URL."""
 
347
 
 
348
    _methodname = 'resolve_lp_path'
 
349
    _authenticated = False
 
350
 
 
351
    def __init__(self, path):
 
352
        if not path:
 
353
            raise errors.InvalidURL(path=path,
 
354
                                    extra="You must specify a project.")
 
355
        self.path = path
 
356
 
 
357
    def _request_params(self):
 
358
        """Return xmlrpc request parameters"""
 
359
        return (self.path,)