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
59 # if there is no cStringIO, fall back to the original
61 from cStringIO import StringIO
63 from StringIO import StringIO
67 class BootServerRequest:
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/")
76 # this is the server to contact if we don't have a bootcd
77 DEFAULT_BOOT_SERVER = "boot.planet-lab.org"
79 BOOTCD_VERSION_FILE = "bootme/ID"
80 BOOTCD_SERVER_FILE = "bootme/BOOTSERVER"
81 BOOTCD_SERVER_CERT_DIR = "bootme/cacert"
82 CACERT_NAME = "cacert.pem"
84 # location of file containing http/https proxy info, if needed
85 PROXY_FILE = '/etc/planetlab/http_proxy'
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
93 # in seconds, how maximum time allowed for connect
94 DEFAULT_CURL_CONNECT_TIMEOUT = 30
96 # in seconds, maximum time allowed for any transfer
97 DEFAULT_CURL_MAX_TRANSFER_TIME = 3600
112 def __init__(self, verbose=0):
114 self.VERBOSE= verbose
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
121 for path in self.CDROM_MOUNT_PATH:
122 self.Message( "Checking existance of boot cd on %s" % path )
124 os.system("/bin/mount %s > /dev/null 2>&1" % path )
126 version_file= path + self.BOOTCD_VERSION_FILE
127 self.Message( "Looking for version file %s" % version_file )
129 if os.access(version_file, os.R_OK) == 0:
130 self.Message( "No boot cd found." );
132 self.Message( "Found boot cd." )
139 # check the version of the boot cd, and locate the certs
140 self.Message( "Getting boot cd version." )
142 versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)")
144 bootcd_version_f= file(version_file,"r")
145 line= string.strip(bootcd_version_f.readline())
146 bootcd_version_f.close()
148 match= versionRegExp.findall(line)
150 (self.BOOTCD_VERSION)= match[0]
152 # right now, all the versions of the bootcd are supported,
153 # so no need to check it
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." %
161 bootservers_f= file(server_list,"r")
162 bootservers= bootservers_f.readlines()
163 bootservers_f.close()
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
173 self.Message( "Set of servers to contact: %s" %
174 str(self.BOOTSERVER_CERTS) )
176 self.Message( "Using default boot server address." )
177 self.BOOTSERVER_CERTS[self.DEFAULT_BOOT_SERVER]= ""
180 def CheckProxy( self ):
181 # see if we have any proxy info from the machine
183 self.Message( "Checking existance of proxy config file..." )
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())
189 self.Message( "Using proxy %s." % self.PROXY )
191 self.Message( "Not using any proxy." )
195 def Message( self, Msg ):
201 def Error( self, Msg ):
202 sys.stderr.write( Msg + "\n" )
206 def Warning( self, Msg ):
211 def MakeRequest( self, PartialPath, GetVars,
212 PostVars, DoSSL, DoCertCheck,
213 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
214 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
217 buffer = tempfile.NamedTemporaryFile()
219 ok = self.DownloadFile(PartialPath, GetVars, PostVars,
220 DoSSL, DoCertCheck, buffer.name,
225 # check the code, return the string only if it was successfull
232 def DownloadFile(self, PartialPath, GetVars, PostVars,
233 DoSSL, DoCertCheck, DestFilePath,
234 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
235 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
238 self.Message( "Attempting to retrieve %s" % PartialPath )
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" )
245 if DoSSL and not PYCURL_LOADED:
246 self.Warning( "Using SSL without pycurl will by default " \
247 "check at least standard certs." )
249 # ConnectTimeout has to be greater than 0
250 if ConnectTimeout <= 0:
251 self.Error( "Connect timeout must be greater than zero.\n" )
259 # setup the post and get vars for the request
262 postdata = urllib.urlencode(PostVars)
263 self.Message( "Posting data:\n%s\n" % postdata )
267 getstr= "?" + urllib.urlencode(GetVars)
268 self.Message( "Get data:\n%s\n" % getstr )
270 # now, attempt to make the request, starting at the first
273 for server in self.BOOTSERVER_CERTS:
274 self.Message( "Contacting server %s." % server )
276 certpath = self.BOOTSERVER_CERTS[server]
279 # output what we are going to be doing
280 self.Message( "Connect timeout is %s seconds" % \
283 self.Message( "Max transfer time is %s seconds" % \
287 url = "https://%s/%s%s" % (server,PartialPath,getstr)
289 if DoCertCheck and PYCURL_LOADED:
290 self.Message( "Using SSL version %d and verifying peer." %
291 self.CURL_SSL_VERSION )
293 self.Message( "Using SSL version %d." %
294 self.CURL_SSL_VERSION )
296 url = "http://%s/%s%s" % (server,PartialPath,getstr)
298 self.Message( "URL: %s" % url )
300 # setup a new pycurl instance, or a curl command line string
301 # if we don't have pycurl
306 # don't want curl sending any signals
307 curl.setopt(pycurl.NOSIGNAL, 1)
309 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
310 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
312 # do not follow location when attempting to download a file
313 curl.setopt(pycurl.FOLLOWLOCATION, 0)
316 curl.setopt(pycurl.PROXY, self.PROXY )
319 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
322 curl.setopt(pycurl.CAINFO, certpath)
323 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
326 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
329 curl.setopt(pycurl.POSTFIELDS, postdata)
331 # setup multipart/form-data upload
333 curl.setopt(pycurl.HTTPPOST, FormData)
335 curl.setopt(pycurl.URL, url)
339 "--connect-timeout %d " \
341 "--header Pragma: " \
344 (self.CURL_CMD, ConnectTimeout,
345 MaxTransferTime, DestFilePath)
348 cmdline = cmdline + "--data '" + postdata + "' "
351 cmdline = cmdline + "".join(["--form '" + field + "' " for field in FormData])
354 cmdline = cmdline + "--silent "
357 cmdline = cmdline + "--proxy %s " % self.PROXY
360 cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
363 cmdline = cmdline + "--cacert %s " % certpath
365 cmdline = cmdline + url
367 self.Message( "curl command: %s" % cmdline )
372 # setup the output file
373 outfile = open(DestFilePath,"wb")
375 self.Message( "Opened output file %s" % DestFilePath )
377 curl.setopt(pycurl.WRITEDATA, outfile)
379 self.Message( "Fetching..." )
381 self.Message( "Done." )
383 http_result= curl.getinfo(pycurl.HTTP_CODE)
387 self.Message( "Results saved in %s" % DestFilePath )
389 # check the code, return 1 if successfull
390 if http_result == self.HTTP_SUCCESS:
391 self.Message( "Successfull!" )
394 self.Message( "Failure, resultant http code: %d" % \
397 except pycurl.error, err:
399 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
400 (server,errno,errstr) )
402 if not outfile.closed:
404 os.unlink(DestFilePath)
410 self.Message( "Fetching..." )
411 rc = os.system(cmdline)
412 self.Message( "Done." )
416 os.unlink( DestFilePath )
419 self.Message( "Failure, resultant curl code: %d" % rc )
420 self.Message( "Removed %s" % DestFilePath )
422 self.Message( "Successfull!" )
425 self.Error( "Unable to successfully contact any boot servers.\n" )
434 Usage: BootServerRequest.py [options] <partialpath>
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
445 if __name__ == "__main__":
448 # check out our command line options
450 opt_list, arg_list = getopt.getopt(sys.argv[1:],
452 [ "output=", "verbose", \
453 "help","ssl","checkcert"])
460 for opt, arg in opt_list:
461 if opt in ("-h","--help"):
465 if opt in ("-c","--checkcert"):
468 if opt in ("-s","--ssl"):
471 if opt in ("-o","--output"):
477 if len(arg_list) != 1:
480 partialpath= arg_list[0]
481 if string.lower(partialpath[:4]) == "http":
488 # got the command line args straightened out
489 requestor= BootServerRequest(verbose)
492 requestor.DownloadFile( partialpath, None, None, ssl,
493 checkcert, output_file)
495 result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)