3 # Copyright (c) 2003 Intel Corporation
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
10 # * Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
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.
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.
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.
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
58 # if there is no cStringIO, fall back to the original
60 from cStringIO import StringIO
62 from StringIO import StringIO
66 class BootServerRequest:
70 # all possible places to check the cdrom mount point.
71 # /mnt/cdrom is typically after the machine has come up,
72 # and /usr is when the boot cd is running
73 CDROM_MOUNT_PATH = ("/mnt/cdrom/","/usr/")
75 # this is the server to contact if we don't have a bootcd
76 DEFAULT_BOOT_SERVER = "boot.planet-lab.org"
78 BOOTCD_VERSION_FILE = "bootme/ID"
79 BOOTCD_SERVER_FILE = "bootme/BOOTSERVER"
80 BOOTCD_SERVER_CERT_DIR = "bootme/cacert"
81 CACERT_NAME = "cacert.pem"
83 # location of file containing http/https proxy info, if needed
84 PROXY_FILE = '/etc/planetlab/http_proxy'
86 # location of curl executable, if pycurl isn't available
87 # and the DownloadFile method is called (backup, only
88 # really need for the boot cd environment where pycurl
92 # in seconds, how maximum time allowed for connect
93 DEFAULT_CURL_CONNECT_TIMEOUT = 30
95 # in seconds, maximum time allowed for any transfer
96 DEFAULT_CURL_MAX_TRANSFER_TIME = 3600
111 def __init__(self, verbose=0):
113 self.VERBOSE= verbose
115 # see if we have a boot cd mounted by checking for the version file
116 # if HAS_BOOTCD == 0 then either the machine doesn't have
117 # a boot cd, or something else is mounted
120 for path in self.CDROM_MOUNT_PATH:
121 self.Message( "Checking existance of boot cd on %s" % path )
123 os.system("/bin/mount %s > /dev/null 2>&1" % path )
125 version_file= path + self.BOOTCD_VERSION_FILE
126 self.Message( "Looking for version file %s" % version_file )
128 if os.access(version_file, os.R_OK) == 0:
129 self.Message( "No boot cd found." );
131 self.Message( "Found boot cd." )
138 # check the version of the boot cd, and locate the certs
139 self.Message( "Getting boot cd version." )
141 versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)")
143 bootcd_version_f= file(version_file,"r")
144 line= string.strip(bootcd_version_f.readline())
145 bootcd_version_f.close()
147 match= versionRegExp.findall(line)
149 (self.BOOTCD_VERSION)= match[0]
151 # right now, all the versions of the bootcd are supported,
152 # so no need to check it
154 # create a list of the servers we should
155 # attempt to contact, and the certs for each
156 server_list= path + self.BOOTCD_SERVER_FILE
157 self.Message( "Getting list of servers off of cd from %s." %
160 bootservers_f= file(server_list,"r")
161 bootservers= bootservers_f.readlines()
162 bootservers_f.close()
164 for bootserver in bootservers:
165 bootserver = string.strip(bootserver)
166 cacert_path= "%s/%s/%s/%s" % \
167 (path,self.BOOTCD_SERVER_CERT_DIR,
168 bootserver,self.CACERT_NAME)
169 if os.access(cacert_path, os.R_OK):
170 self.BOOTSERVER_CERTS[bootserver]= cacert_path
172 self.Message( "Set of servers to contact: %s" %
173 str(self.BOOTSERVER_CERTS) )
175 self.Message( "Using default boot server address." )
176 self.BOOTSERVER_CERTS[self.DEFAULT_BOOT_SERVER]= ""
179 def CheckProxy( self ):
180 # see if we have any proxy info from the machine
182 self.Message( "Checking existance of proxy config file..." )
184 if os.access(self.PROXY_FILE, os.R_OK) and \
185 os.path.isfile(self.PROXY_FILE):
186 self.PROXY= string.strip(file(self.PROXY_FILE,'r').readline())
188 self.Message( "Using proxy %s." % self.PROXY )
190 self.Message( "Not using any proxy." )
194 def Message( self, Msg ):
200 def Error( self, Msg ):
201 sys.stderr.write( Msg + "\n" )
205 def Warning( self, Msg ):
210 def MakeRequest( self, PartialPath, GetVars,
211 PostVars, DoSSL, DoCertCheck,
212 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
213 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME):
215 if PYCURL_LOADED == 0:
216 self.Error( "MakeRequest method requires pycurl." )
221 self.Message( "Attempting to retrieve %s" % PartialPath )
223 # we can't do ssl and check the cert if we don't have a bootcd
224 if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
225 self.Error( "No boot cd exists (needed to use -c and -s.\n" )
228 # didn't pass a path in? just get the root doc
229 if PartialPath == "":
232 # ConnectTimeout has to be greater than 0
233 if ConnectTimeout <= 0:
234 self.Error( "Connect timeout must be greater than zero.\n" )
237 # setup the post and get vars for the request
240 postdata = urllib.urlencode(PostVars)
241 self.Message( "Posting data:\n%s\n" % postdata )
247 getstr= "?" + urllib.urlencode(GetVars)
248 self.Message( "Get data:\n%s\n" % getstr )
250 # now, attempt to make the request, starting at the first
252 for server in self.BOOTSERVER_CERTS:
253 self.Message( "Contacting server %s." % server )
255 certpath = self.BOOTSERVER_CERTS[server]
259 # don't want curl sending any signals
260 curl.setopt(pycurl.NOSIGNAL, 1)
262 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
263 self.Message( "Connect timeout is %s seconds" % \
266 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
267 self.Message( "Max transfer time is %s seconds" % \
270 curl.setopt(pycurl.FOLLOWLOCATION, 1)
271 curl.setopt(pycurl.MAXREDIRS, 2)
274 curl.setopt(pycurl.PROXY, self.PROXY )
277 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
279 url = "https://%s/%s%s" % (server,PartialPath,getstr)
281 curl.setopt(pycurl.CAINFO, certpath)
282 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
283 self.Message( "Using SSL version %d and verifying peer." % \
284 self.CURL_SSL_VERSION )
286 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
287 self.Message( "Using SSL version %d" % \
288 self.CURL_SSL_VERSION )
290 url = "http://%s/%s%s" % (server,PartialPath,getstr)
293 curl.setopt(pycurl.POSTFIELDS, postdata)
295 curl.setopt(pycurl.URL, url)
296 self.Message( "URL: %s" % url )
298 # setup the output buffer
300 curl.setopt(pycurl.WRITEFUNCTION, buffer.write)
303 self.Message( "Fetching..." )
305 self.Message( "Done." )
307 http_result= curl.getinfo(pycurl.HTTP_CODE)
310 # check the code, return the string only if it was successfull
311 if http_result == self.HTTP_SUCCESS:
312 self.Message( "Successfull!" )
313 return buffer.getvalue()
315 self.Message( "Failure, resultant http code: %d" % \
319 except pycurl.error, err:
321 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
322 (server,errno,errstr) )
324 self.Error( "Unable to successfully contact any boot servers.\n" )
329 def DownloadFile(self, PartialPath, GetVars, PostVars,
330 DoSSL, DoCertCheck, DestFilePath,
331 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
332 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME):
334 self.Message( "Attempting to retrieve %s" % PartialPath )
336 # we can't do ssl and check the cert if we don't have a bootcd
337 if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
338 self.Error( "No boot cd exists (needed to use -c and -s.\n" )
341 if DoSSL and not PYCURL_LOADED:
342 self.Warning( "Using SSL without pycurl will by default " \
343 "check at least standard certs." )
345 # ConnectTimeout has to be greater than 0
346 if ConnectTimeout <= 0:
347 self.Error( "Connect timeout must be greater than zero.\n" )
355 # setup the post and get vars for the request
358 postdata = urllib.urlencode(PostVars)
359 self.Message( "Posting data:\n%s\n" % postdata )
363 getstr= "?" + urllib.urlencode(GetVars)
364 self.Message( "Get data:\n%s\n" % getstr )
366 # now, attempt to make the request, starting at the first
369 for server in self.BOOTSERVER_CERTS:
370 self.Message( "Contacting server %s." % server )
372 certpath = self.BOOTSERVER_CERTS[server]
375 # output what we are going to be doing
376 self.Message( "Connect timeout is %s seconds" % \
379 self.Message( "Max transfer time is %s seconds" % \
383 url = "https://%s/%s%s" % (server,PartialPath,getstr)
385 if DoCertCheck and PYCURL_LOADED:
386 self.Message( "Using SSL version %d and verifying peer." %
387 self.CURL_SSL_VERSION )
389 self.Message( "Using SSL version %d." %
390 self.CURL_SSL_VERSION )
392 url = "http://%s/%s%s" % (server,PartialPath,getstr)
394 self.Message( "URL: %s" % url )
396 # setup a new pycurl instance, or a curl command line string
397 # if we don't have pycurl
402 # don't want curl sending any signals
403 curl.setopt(pycurl.NOSIGNAL, 1)
405 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
406 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
408 # do not follow location when attempting to download a file
409 curl.setopt(pycurl.FOLLOWLOCATION, 0)
412 curl.setopt(pycurl.PROXY, self.PROXY )
415 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
418 curl.setopt(pycurl.CAINFO, certpath)
419 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
422 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
425 curl.setopt(pycurl.POSTFIELDS, postdata)
427 curl.setopt(pycurl.URL, url)
431 "--connect-timeout %d " \
433 "--header Pragma: " \
436 (self.CURL_CMD, ConnectTimeout,
437 MaxTransferTime, DestFilePath)
440 cmdline = cmdline + "--data '" + postdata + "' "
443 cmdline = cmdline + "--silent "
446 cmdline = cmdline + "--proxy %s " % self.PROXY
449 cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
452 cmdline = cmdline + "--cacert %s " % certpath
454 cmdline = cmdline + url
456 self.Message( "curl command: %s" % cmdline )
461 # setup the output file
462 outfile = open(DestFilePath,"wb")
464 self.Message( "Opened output file %s" % DestFilePath )
466 curl.setopt(pycurl.WRITEDATA, outfile)
468 self.Message( "Fetching..." )
470 self.Message( "Done." )
472 http_result= curl.getinfo(pycurl.HTTP_CODE)
476 self.Message( "Results saved in %s" % DestFilePath )
478 # check the code, return 1 if successfull
479 if http_result == self.HTTP_SUCCESS:
480 self.Message( "Successfull!" )
483 self.Message( "Failure, resultant http code: %d" % \
486 except pycurl.error, err:
488 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
489 (server,errno,errstr) )
491 if not outfile.closed:
493 os.unlink(DestFilePath)
499 self.Message( "Fetching..." )
500 rc = os.system(cmdline)
501 self.Message( "Done." )
505 os.unlink( DestFilePath )
508 self.Message( "Failure, resultant curl code: %d" % rc )
509 self.Message( "Removed %s" % DestFilePath )
511 self.Message( "Successfull!" )
514 self.Error( "Unable to successfully contact any boot servers.\n" )
523 Usage: BootServerRequest.py [options] <partialpath>
525 -c/--checkcert Check SSL certs. Ignored if -s/--ssl missing.
526 -h/--help This help text
527 -o/--output <file> Write result to file
528 -s/--ssl Make the request over HTTPS
529 -v Makes the operation more talkative
534 if __name__ == "__main__":
537 # check out our command line options
539 opt_list, arg_list = getopt.getopt(sys.argv[1:],
541 [ "output=", "verbose", \
542 "help","ssl","checkcert"])
549 for opt, arg in opt_list:
550 if opt in ("-h","--help"):
554 if opt in ("-c","--checkcert"):
557 if opt in ("-s","--ssl"):
560 if opt in ("-o","--output"):
566 if len(arg_list) != 1:
569 partialpath= arg_list[0]
570 if string.lower(partialpath[:4]) == "http":
577 # got the command line args straightened out
578 requestor= BootServerRequest(verbose)
581 requestor.DownloadFile( partialpath, None, None, ssl,
582 checkcert, output_file)
584 result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)