b2f03a16658c9b552bdc68a788861707deffc365
[bootmanager.git] / source / BootServerRequest.py
1 #!/usr/bin/python2
2
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met:
9
10 #     * Redistributions of source code must retain the above copyright
11 #       notice, this list of conditions and the following disclaimer.
12
13 #     * Redistributions in binary form must reproduce the above
14 #       copyright notice, this list of conditions and the following
15 #       disclaimer in the documentation and/or other materials provided
16 #       with the distribution.
17
18 #     * Neither the name of the Intel Corporation nor the names of its
19 #       contributors may be used to endorse or promote products derived
20 #       from this software without specific prior written permission.
21
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
26 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34 # EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF
35 # YOUR JURISDICTION. It is licensee's responsibility to comply with any
36 # export regulations applicable in licensee's jurisdiction. Under
37 # CURRENT (May 2000) U.S. export regulations this software is eligible
38 # for export from the U.S. and can be downloaded by or otherwise
39 # exported or reexported worldwide EXCEPT to U.S. embargoed destinations
40 # which include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan,
41 # Afghanistan and any other country to which the U.S. has embargoed
42 # goods and services.
43
44
45 import os, sys
46 import re
47 import string
48 import urllib
49 import tempfile
50
51 # try to load pycurl
52 try:
53     import pycurl
54     PYCURL_LOADED= 1
55 except:
56     PYCURL_LOADED= 0
57
58
59 # if there is no cStringIO, fall back to the original
60 try:
61     from cStringIO import StringIO
62 except:
63     from StringIO import StringIO
64
65
66
67 class BootServerRequest:
68
69     VERBOSE = 0
70
71     # all possible places to check the cdrom mount point.
72     # /mnt/cdrom is typically after the machine has come up,
73     # and /usr is when the boot cd is running
74     CDROM_MOUNT_PATH = ("/mnt/cdrom/","/usr/")
75
76     # this is the server to contact if we don't have a bootcd
77     DEFAULT_BOOT_SERVER = "boot.planet-lab.org"
78
79     BOOTCD_VERSION_FILE = "bootme/ID"
80     BOOTCD_SERVER_FILE = "bootme/BOOTSERVER"
81     BOOTCD_SERVER_CERT_DIR = "bootme/cacert"
82     CACERT_NAME = "cacert.pem"
83     
84     # location of file containing http/https proxy info, if needed
85     PROXY_FILE = '/etc/planetlab/http_proxy'
86
87     # location of curl executable, if pycurl isn't available
88     # and the DownloadFile method is called (backup, only
89     # really need for the boot cd environment where pycurl
90     # doesn't exist
91     CURL_CMD = 'curl'
92
93     # in seconds, how maximum time allowed for connect
94     DEFAULT_CURL_CONNECT_TIMEOUT = 30
95
96     # in seconds, maximum time allowed for any transfer
97     DEFAULT_CURL_MAX_TRANSFER_TIME = 3600
98
99     CURL_SSL_VERSION = 3
100
101     HTTP_SUCCESS = 200
102
103     # proxy variables
104     USE_PROXY = 0
105     PROXY = 0
106
107     # bootcd variables
108     HAS_BOOTCD = 0
109     BOOTCD_VERSION = ""
110     BOOTSERVER_CERTS= {}
111
112     def __init__(self, verbose=0):
113
114         self.VERBOSE= verbose
115             
116         # see if we have a boot cd mounted by checking for the version file
117         # if HAS_BOOTCD == 0 then either the machine doesn't have
118         # a boot cd, or something else is mounted
119         self.HAS_BOOTCD = 0
120
121         for path in self.CDROM_MOUNT_PATH:
122             self.Message( "Checking existance of boot cd on %s" % path )
123
124             os.system("/bin/mount %s > /dev/null 2>&1" % path )
125                 
126             version_file= path + self.BOOTCD_VERSION_FILE
127             self.Message( "Looking for version file %s" % version_file )
128
129             if os.access(version_file, os.R_OK) == 0:
130                 self.Message( "No boot cd found." );
131             else:
132                 self.Message( "Found boot cd." )
133                 self.HAS_BOOTCD=1
134                 break
135
136
137         if self.HAS_BOOTCD:
138
139             # check the version of the boot cd, and locate the certs
140             self.Message( "Getting boot cd version." )
141         
142             versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)")
143                 
144             bootcd_version_f= file(version_file,"r")
145             line= string.strip(bootcd_version_f.readline())
146             bootcd_version_f.close()
147             
148             match= versionRegExp.findall(line)
149             if match:
150                 (self.BOOTCD_VERSION)= match[0]
151             
152             # right now, all the versions of the bootcd are supported,
153             # so no need to check it
154             
155             # create a list of the servers we should
156             # attempt to contact, and the certs for each
157             server_list= path + self.BOOTCD_SERVER_FILE
158             self.Message( "Getting list of servers off of cd from %s." %
159                           server_list )
160             
161             bootservers_f= file(server_list,"r")
162             bootservers= bootservers_f.readlines()
163             bootservers_f.close()
164             
165             for bootserver in bootservers:
166                 bootserver = string.strip(bootserver)
167                 cacert_path= "%s/%s/%s/%s" % \
168                              (path,self.BOOTCD_SERVER_CERT_DIR,
169                               bootserver,self.CACERT_NAME)
170                 if os.access(cacert_path, os.R_OK):
171                     self.BOOTSERVER_CERTS[bootserver]= cacert_path
172
173             self.Message( "Set of servers to contact: %s" %
174                           str(self.BOOTSERVER_CERTS) )
175         else:
176             self.Message( "Using default boot server address." )
177             self.BOOTSERVER_CERTS[self.DEFAULT_BOOT_SERVER]= ""
178
179
180     def CheckProxy( self ):
181         # see if we have any proxy info from the machine
182         self.USE_PROXY= 0
183         self.Message( "Checking existance of proxy config file..." )
184         
185         if os.access(self.PROXY_FILE, os.R_OK) and \
186                os.path.isfile(self.PROXY_FILE):
187             self.PROXY= string.strip(file(self.PROXY_FILE,'r').readline())
188             self.USE_PROXY= 1
189             self.Message( "Using proxy %s." % self.PROXY )
190         else:
191             self.Message( "Not using any proxy." )
192
193
194
195     def Message( self, Msg ):
196         if( self.VERBOSE ):
197             print( Msg )
198
199
200
201     def Error( self, Msg ):
202         sys.stderr.write( Msg + "\n" )
203
204
205
206     def Warning( self, Msg ):
207         self.Error(Msg)
208
209
210
211     def MakeRequest( self, PartialPath, GetVars,
212                      PostVars, DoSSL, DoCertCheck,
213                      ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
214                      MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
215                      FormData= None):
216
217         buffer = tempfile.NamedTemporaryFile()
218
219         ok = self.DownloadFile(PartialPath, GetVars, PostVars,
220                                DoSSL, DoCertCheck, buffer.name,
221                                ConnectTimeout,
222                                MaxTransferTime,
223                                FormData)
224
225         # check the code, return the string only if it was successfull
226         if ok:
227             buffer.seek(0)
228             return buffer.read()
229         else:
230             return None
231
232     def DownloadFile(self, PartialPath, GetVars, PostVars,
233                      DoSSL, DoCertCheck, DestFilePath,
234                      ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
235                      MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
236                      FormData= None):
237
238         self.Message( "Attempting to retrieve %s" % PartialPath )
239
240         # we can't do ssl and check the cert if we don't have a bootcd
241         if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
242             self.Error( "No boot cd exists (needed to use -c and -s.\n" )
243             return 0
244
245         if DoSSL and not PYCURL_LOADED:
246             self.Warning( "Using SSL without pycurl will by default " \
247                           "check at least standard certs." )
248
249         # ConnectTimeout has to be greater than 0
250         if ConnectTimeout <= 0:
251             self.Error( "Connect timeout must be greater than zero.\n" )
252             return 0
253
254
255         self.CheckProxy()
256
257         dopostdata= 0
258
259         # setup the post and get vars for the request
260         if PostVars:
261             dopostdata= 1
262             postdata = urllib.urlencode(PostVars)
263             self.Message( "Posting data:\n%s\n" % postdata )
264             
265         getstr= ""
266         if GetVars:
267             getstr= "?" + urllib.urlencode(GetVars)
268             self.Message( "Get data:\n%s\n" % getstr )
269
270         # now, attempt to make the request, starting at the first
271         # server in the list
272         
273         for server in self.BOOTSERVER_CERTS:
274             self.Message( "Contacting server %s." % server )
275                         
276             certpath = self.BOOTSERVER_CERTS[server]
277
278             
279             # output what we are going to be doing
280             self.Message( "Connect timeout is %s seconds" % \
281                           ConnectTimeout )
282
283             self.Message( "Max transfer time is %s seconds" % \
284                           MaxTransferTime )
285
286             if DoSSL:
287                 url = "https://%s/%s%s" % (server,PartialPath,getstr)
288                 
289                 if DoCertCheck and PYCURL_LOADED:
290                     self.Message( "Using SSL version %d and verifying peer." %
291                              self.CURL_SSL_VERSION )
292                 else:
293                     self.Message( "Using SSL version %d." %
294                              self.CURL_SSL_VERSION )
295             else:
296                 url = "http://%s/%s%s" % (server,PartialPath,getstr)
297                 
298             self.Message( "URL: %s" % url )
299             
300             # setup a new pycurl instance, or a curl command line string
301             # if we don't have pycurl
302             
303             if PYCURL_LOADED:
304                 curl= pycurl.Curl()
305
306                 # don't want curl sending any signals
307                 curl.setopt(pycurl.NOSIGNAL, 1)
308             
309                 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
310                 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
311
312                 # do not follow location when attempting to download a file
313                 curl.setopt(pycurl.FOLLOWLOCATION, 0)
314
315                 if self.USE_PROXY:
316                     curl.setopt(pycurl.PROXY, self.PROXY )
317
318                 if DoSSL:
319                     curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
320                 
321                     if DoCertCheck:
322                         curl.setopt(pycurl.CAINFO, certpath)
323                         curl.setopt(pycurl.SSL_VERIFYPEER, 2)
324                         
325                     else:
326                         curl.setopt(pycurl.SSL_VERIFYPEER, 0)
327                 
328                 if dopostdata:
329                     curl.setopt(pycurl.POSTFIELDS, postdata)
330
331                 # setup multipart/form-data upload
332                 if FormData:
333                     curl.setopt(pycurl.HTTPPOST, FormData)
334
335                 curl.setopt(pycurl.URL, url)
336             else:
337
338                 cmdline = "%s " \
339                           "--connect-timeout %d " \
340                           "--max-time %d " \
341                           "--header Pragma: " \
342                           "--output %s " \
343                           "--fail " % \
344                           (self.CURL_CMD, ConnectTimeout,
345                            MaxTransferTime, DestFilePath)
346
347                 if dopostdata:
348                     cmdline = cmdline + "--data '" + postdata + "' "
349
350                 if FormData:
351                     cmdline = cmdline + "".join(["--form '" + field + "' " for field in FormData])
352
353                 if not self.VERBOSE:
354                     cmdline = cmdline + "--silent "
355                     
356                 if self.USE_PROXY:
357                     cmdline = cmdline + "--proxy %s " % self.PROXY
358
359                 if DoSSL:
360                     cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
361
362                     if DoCertCheck:
363                         cmdline = cmdline + "--cacert %s " % certpath
364                  
365                 cmdline = cmdline + url
366
367                 self.Message( "curl command: %s" % cmdline )
368                 
369                 
370             if PYCURL_LOADED:
371                 try:
372                     # setup the output file
373                     outfile = open(DestFilePath,"wb")
374                     
375                     self.Message( "Opened output file %s" % DestFilePath )
376                 
377                     curl.setopt(pycurl.WRITEDATA, outfile)
378                 
379                     self.Message( "Fetching..." )
380                     curl.perform()
381                     self.Message( "Done." )
382                 
383                     http_result= curl.getinfo(pycurl.HTTP_CODE)
384                     curl.close()
385                 
386                     outfile.close()
387                     self.Message( "Results saved in %s" % DestFilePath )
388
389                     # check the code, return 1 if successfull
390                     if http_result == self.HTTP_SUCCESS:
391                         self.Message( "Successfull!" )
392                         return 1
393                     else:
394                         self.Message( "Failure, resultant http code: %d" % \
395                                       http_result )
396
397                 except pycurl.error, err:
398                     errno, errstr= err
399                     self.Error( "connect to %s failed; curl error %d: '%s'\n" %
400                        (server,errno,errstr) )
401         
402                 if not outfile.closed:
403                     try:
404                         os.unlink(DestFilePath)
405                         outfile.close
406                     except OSError:
407                         pass
408
409             else:
410                 self.Message( "Fetching..." )
411                 rc = os.system(cmdline)
412                 self.Message( "Done." )
413                 
414                 if rc != 0:
415                     try:
416                         os.unlink( DestFilePath )
417                     except OSError:
418                         pass
419                     self.Message( "Failure, resultant curl code: %d" % rc )
420                     self.Message( "Removed %s" % DestFilePath )
421                 else:
422                     self.Message( "Successfull!" )
423                     return 1
424             
425         self.Error( "Unable to successfully contact any boot servers.\n" )
426         return 0
427
428
429
430
431 def usage():
432     print(
433     """
434 Usage: BootServerRequest.py [options] <partialpath>
435 Options:
436  -c/--checkcert        Check SSL certs. Ignored if -s/--ssl missing.
437  -h/--help             This help text
438  -o/--output <file>    Write result to file
439  -s/--ssl              Make the request over HTTPS
440  -v                    Makes the operation more talkative
441 """);  
442
443
444
445 if __name__ == "__main__":
446     import getopt
447     
448     # check out our command line options
449     try:
450         opt_list, arg_list = getopt.getopt(sys.argv[1:],
451                                            "o:vhsc",
452                                            [ "output=", "verbose", \
453                                              "help","ssl","checkcert"])
454
455         ssl= 0
456         checkcert= 0
457         output_file= None
458         verbose= 0
459         
460         for opt, arg in opt_list:
461             if opt in ("-h","--help"):
462                 usage(0)
463                 sys.exit()
464             
465             if opt in ("-c","--checkcert"):
466                 checkcert= 1
467             
468             if opt in ("-s","--ssl"):
469                 ssl= 1
470
471             if opt in ("-o","--output"):
472                 output_file= arg
473
474             if opt == "-v":
475                 verbose= 1
476     
477         if len(arg_list) != 1:
478             raise Exception
479
480         partialpath= arg_list[0]
481         if string.lower(partialpath[:4]) == "http":
482             raise Exception
483
484     except:
485         usage()
486         sys.exit(2)
487
488     # got the command line args straightened out
489     requestor= BootServerRequest(verbose)
490         
491     if output_file:
492         requestor.DownloadFile( partialpath, None, None, ssl,
493                                 checkcert, output_file)
494     else:
495         result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)
496         if result:
497             print result
498         else:
499             sys.exit(1)