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 if hasattr(tempfile, "NamedTemporaryFile"):
218 buffer = tempfile.NamedTemporaryFile()
219 buffer_name = buffer.name
221 buffer_name = tempfile.mktemp("MakeRequest")
222 buffer = open(buffer_name, "w+")
224 ok = self.DownloadFile(PartialPath, GetVars, PostVars,
225 DoSSL, DoCertCheck, buffer_name,
230 # check the code, return the string only if it was successfull
237 def DownloadFile(self, PartialPath, GetVars, PostVars,
238 DoSSL, DoCertCheck, DestFilePath,
239 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
240 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
243 self.Message( "Attempting to retrieve %s" % PartialPath )
245 # we can't do ssl and check the cert if we don't have a bootcd
246 if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
247 self.Error( "No boot cd exists (needed to use -c and -s.\n" )
250 if DoSSL and not PYCURL_LOADED:
251 self.Warning( "Using SSL without pycurl will by default " \
252 "check at least standard certs." )
254 # ConnectTimeout has to be greater than 0
255 if ConnectTimeout <= 0:
256 self.Error( "Connect timeout must be greater than zero.\n" )
264 # setup the post and get vars for the request
267 postdata = urllib.urlencode(PostVars)
268 self.Message( "Posting data:\n%s\n" % postdata )
272 getstr= "?" + urllib.urlencode(GetVars)
273 self.Message( "Get data:\n%s\n" % getstr )
275 # now, attempt to make the request, starting at the first
278 for server in self.BOOTSERVER_CERTS:
279 self.Message( "Contacting server %s." % server )
281 certpath = self.BOOTSERVER_CERTS[server]
284 # output what we are going to be doing
285 self.Message( "Connect timeout is %s seconds" % \
288 self.Message( "Max transfer time is %s seconds" % \
292 url = "https://%s/%s%s" % (server,PartialPath,getstr)
294 if DoCertCheck and PYCURL_LOADED:
295 self.Message( "Using SSL version %d and verifying peer." %
296 self.CURL_SSL_VERSION )
298 self.Message( "Using SSL version %d." %
299 self.CURL_SSL_VERSION )
301 url = "http://%s/%s%s" % (server,PartialPath,getstr)
303 self.Message( "URL: %s" % url )
305 # setup a new pycurl instance, or a curl command line string
306 # if we don't have pycurl
311 # don't want curl sending any signals
312 curl.setopt(pycurl.NOSIGNAL, 1)
314 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
315 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
317 # do not follow location when attempting to download a file
318 curl.setopt(pycurl.FOLLOWLOCATION, 0)
321 curl.setopt(pycurl.PROXY, self.PROXY )
324 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
327 curl.setopt(pycurl.CAINFO, certpath)
328 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
331 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
334 curl.setopt(pycurl.POSTFIELDS, postdata)
336 # setup multipart/form-data upload
338 curl.setopt(pycurl.HTTPPOST, FormData)
340 curl.setopt(pycurl.URL, url)
344 "--connect-timeout %d " \
346 "--header Pragma: " \
349 (self.CURL_CMD, ConnectTimeout,
350 MaxTransferTime, DestFilePath)
353 cmdline = cmdline + "--data '" + postdata + "' "
356 cmdline = cmdline + "".join(["--form '" + field + "' " for field in FormData])
359 cmdline = cmdline + "--silent "
362 cmdline = cmdline + "--proxy %s " % self.PROXY
365 cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
368 cmdline = cmdline + "--cacert %s " % certpath
370 cmdline = cmdline + url
372 self.Message( "curl command: %s" % cmdline )
377 # setup the output file
378 outfile = open(DestFilePath,"wb")
380 self.Message( "Opened output file %s" % DestFilePath )
382 curl.setopt(pycurl.WRITEDATA, outfile)
384 self.Message( "Fetching..." )
386 self.Message( "Done." )
388 http_result= curl.getinfo(pycurl.HTTP_CODE)
392 self.Message( "Results saved in %s" % DestFilePath )
394 # check the code, return 1 if successfull
395 if http_result == self.HTTP_SUCCESS:
396 self.Message( "Successfull!" )
399 self.Message( "Failure, resultant http code: %d" % \
402 except pycurl.error, err:
404 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
405 (server,errno,errstr) )
407 if not outfile.closed:
409 os.unlink(DestFilePath)
415 self.Message( "Fetching..." )
416 rc = os.system(cmdline)
417 self.Message( "Done." )
421 os.unlink( DestFilePath )
424 self.Message( "Failure, resultant curl code: %d" % rc )
425 self.Message( "Removed %s" % DestFilePath )
427 self.Message( "Successfull!" )
430 self.Error( "Unable to successfully contact any boot servers.\n" )
439 Usage: BootServerRequest.py [options] <partialpath>
441 -c/--checkcert Check SSL certs. Ignored if -s/--ssl missing.
442 -h/--help This help text
443 -o/--output <file> Write result to file
444 -s/--ssl Make the request over HTTPS
445 -v Makes the operation more talkative
450 if __name__ == "__main__":
453 # check out our command line options
455 opt_list, arg_list = getopt.getopt(sys.argv[1:],
457 [ "output=", "verbose", \
458 "help","ssl","checkcert"])
465 for opt, arg in opt_list:
466 if opt in ("-h","--help"):
470 if opt in ("-c","--checkcert"):
473 if opt in ("-s","--ssl"):
476 if opt in ("-o","--output"):
482 if len(arg_list) != 1:
485 partialpath= arg_list[0]
486 if string.lower(partialpath[:4]) == "http":
493 # got the command line args straightened out
494 requestor= BootServerRequest(verbose)
497 requestor.DownloadFile( partialpath, None, None, ssl,
498 checkcert, output_file)
500 result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)