3 # Copyright (c) 2003 Intel Corporation
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
23 # if there is no cStringIO, fall back to the original
25 from cStringIO import StringIO
27 from StringIO import StringIO
31 class BootServerRequest:
35 # all possible places to check the cdrom mount point.
36 # /mnt/cdrom is typically after the machine has come up,
37 # and /usr is when the boot cd is running
38 CDROM_MOUNT_PATH = ("/mnt/cdrom/","/usr/")
40 # this is the server to contact if we don't have a bootcd
41 DEFAULT_BOOT_SERVER = "boot.planet-lab.org"
43 BOOTCD_VERSION_FILE = "bootme/ID"
44 BOOTCD_SERVER_FILE = "bootme/BOOTSERVER"
45 BOOTCD_SERVER_CERT_DIR = "bootme/cacert"
46 CACERT_NAME = "cacert.pem"
48 # location of file containing http/https proxy info, if needed
49 PROXY_FILE = '/etc/planetlab/http_proxy'
51 # location of curl executable, if pycurl isn't available
52 # and the DownloadFile method is called (backup, only
53 # really need for the boot cd environment where pycurl
57 # in seconds, how maximum time allowed for connect
58 DEFAULT_CURL_CONNECT_TIMEOUT = 30
60 # in seconds, maximum time allowed for any transfer
61 DEFAULT_CURL_MAX_TRANSFER_TIME = 3600
76 def __init__(self, verbose=0):
80 # see if we have a boot cd mounted by checking for the version file
81 # if HAS_BOOTCD == 0 then either the machine doesn't have
82 # a boot cd, or something else is mounted
85 for path in self.CDROM_MOUNT_PATH:
86 self.Message( "Checking existance of boot cd on %s" % path )
88 os.system("/bin/mount %s > /dev/null 2>&1" % path )
90 version_file= path + self.BOOTCD_VERSION_FILE
91 self.Message( "Looking for version file %s" % version_file )
93 if os.access(version_file, os.R_OK) == 0:
94 self.Message( "No boot cd found." );
96 self.Message( "Found boot cd." )
103 # check the version of the boot cd, and locate the certs
104 self.Message( "Getting boot cd version." )
106 versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)")
108 bootcd_version_f= file(version_file,"r")
109 line= string.strip(bootcd_version_f.readline())
110 bootcd_version_f.close()
112 match= versionRegExp.findall(line)
114 (self.BOOTCD_VERSION)= match[0]
116 # right now, all the versions of the bootcd are supported,
117 # so no need to check it
119 # create a list of the servers we should
120 # attempt to contact, and the certs for each
121 server_list= path + self.BOOTCD_SERVER_FILE
122 self.Message( "Getting list of servers off of cd from %s." %
125 bootservers_f= file(server_list,"r")
126 bootservers= bootservers_f.readlines()
127 bootservers_f.close()
129 for bootserver in bootservers:
130 bootserver = string.strip(bootserver)
131 cacert_path= "%s/%s/%s/%s" % \
132 (path,self.BOOTCD_SERVER_CERT_DIR,
133 bootserver,self.CACERT_NAME)
134 if os.access(cacert_path, os.R_OK):
135 self.BOOTSERVER_CERTS[bootserver]= cacert_path
137 self.Message( "Set of servers to contact: %s" %
138 str(self.BOOTSERVER_CERTS) )
140 self.Message( "Using default boot server address." )
141 self.BOOTSERVER_CERTS[self.DEFAULT_BOOT_SERVER]= ""
144 def CheckProxy( self ):
145 # see if we have any proxy info from the machine
147 self.Message( "Checking existance of proxy config file..." )
149 if os.access(self.PROXY_FILE, os.R_OK) and \
150 os.path.isfile(self.PROXY_FILE):
151 self.PROXY= string.strip(file(self.PROXY_FILE,'r').readline())
153 self.Message( "Using proxy %s." % self.PROXY )
155 self.Message( "Not using any proxy." )
159 def Message( self, Msg ):
165 def Error( self, Msg ):
166 sys.stderr.write( Msg + "\n" )
170 def Warning( self, Msg ):
175 def MakeRequest( self, PartialPath, GetVars,
176 PostVars, DoSSL, DoCertCheck,
177 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
178 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
181 if hasattr(tempfile, "NamedTemporaryFile"):
182 buffer = tempfile.NamedTemporaryFile()
183 buffer_name = buffer.name
185 buffer_name = tempfile.mktemp("MakeRequest")
186 buffer = open(buffer_name, "w+")
188 ok = self.DownloadFile(PartialPath, GetVars, PostVars,
189 DoSSL, DoCertCheck, buffer_name,
194 # check the code, return the string only if it was successfull
201 def DownloadFile(self, PartialPath, GetVars, PostVars,
202 DoSSL, DoCertCheck, DestFilePath,
203 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
204 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
207 self.Message( "Attempting to retrieve %s" % PartialPath )
209 # we can't do ssl and check the cert if we don't have a bootcd
210 if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
211 self.Error( "No boot cd exists (needed to use -c and -s.\n" )
214 if DoSSL and not PYCURL_LOADED:
215 self.Warning( "Using SSL without pycurl will by default " \
216 "check at least standard certs." )
218 # ConnectTimeout has to be greater than 0
219 if ConnectTimeout <= 0:
220 self.Error( "Connect timeout must be greater than zero.\n" )
228 # setup the post and get vars for the request
231 postdata = urllib.urlencode(PostVars)
232 self.Message( "Posting data:\n%s\n" % postdata )
236 getstr= "?" + urllib.urlencode(GetVars)
237 self.Message( "Get data:\n%s\n" % getstr )
239 # now, attempt to make the request, starting at the first
242 for server in self.BOOTSERVER_CERTS:
243 self.Message( "Contacting server %s." % server )
245 certpath = self.BOOTSERVER_CERTS[server]
248 # output what we are going to be doing
249 self.Message( "Connect timeout is %s seconds" % \
252 self.Message( "Max transfer time is %s seconds" % \
256 url = "https://%s/%s%s" % (server,PartialPath,getstr)
258 if DoCertCheck and PYCURL_LOADED:
259 self.Message( "Using SSL version %d and verifying peer." %
260 self.CURL_SSL_VERSION )
262 self.Message( "Using SSL version %d." %
263 self.CURL_SSL_VERSION )
265 url = "http://%s/%s%s" % (server,PartialPath,getstr)
267 self.Message( "URL: %s" % url )
269 # setup a new pycurl instance, or a curl command line string
270 # if we don't have pycurl
275 # don't want curl sending any signals
276 curl.setopt(pycurl.NOSIGNAL, 1)
278 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
279 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
281 # do not follow location when attempting to download a file
282 curl.setopt(pycurl.FOLLOWLOCATION, 0)
285 curl.setopt(pycurl.PROXY, self.PROXY )
288 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
291 curl.setopt(pycurl.CAINFO, certpath)
292 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
295 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
298 curl.setopt(pycurl.POSTFIELDS, postdata)
300 # setup multipart/form-data upload
302 curl.setopt(pycurl.HTTPPOST, FormData)
304 curl.setopt(pycurl.URL, url)
308 "--connect-timeout %d " \
310 "--header Pragma: " \
313 (self.CURL_CMD, ConnectTimeout,
314 MaxTransferTime, DestFilePath)
317 cmdline = cmdline + "--data '" + postdata + "' "
320 cmdline = cmdline + "".join(["--form '" + field + "' " for field in FormData])
323 cmdline = cmdline + "--silent "
326 cmdline = cmdline + "--proxy %s " % self.PROXY
329 cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
332 cmdline = cmdline + "--cacert %s " % certpath
334 cmdline = cmdline + url
336 self.Message( "curl command: %s" % cmdline )
341 # setup the output file
342 outfile = open(DestFilePath,"wb")
344 self.Message( "Opened output file %s" % DestFilePath )
346 curl.setopt(pycurl.WRITEDATA, outfile)
348 self.Message( "Fetching..." )
350 self.Message( "Done." )
352 http_result= curl.getinfo(pycurl.HTTP_CODE)
356 self.Message( "Results saved in %s" % DestFilePath )
358 # check the code, return 1 if successfull
359 if http_result == self.HTTP_SUCCESS:
360 self.Message( "Successfull!" )
363 self.Message( "Failure, resultant http code: %d" % \
366 except pycurl.error, err:
368 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
369 (server,errno,errstr) )
371 if not outfile.closed:
373 os.unlink(DestFilePath)
379 self.Message( "Fetching..." )
380 rc = os.system(cmdline)
381 self.Message( "Done." )
385 os.unlink( DestFilePath )
388 self.Message( "Failure, resultant curl code: %d" % rc )
389 self.Message( "Removed %s" % DestFilePath )
391 self.Message( "Successfull!" )
394 self.Error( "Unable to successfully contact any boot servers.\n" )
403 Usage: BootServerRequest.py [options] <partialpath>
405 -c/--checkcert Check SSL certs. Ignored if -s/--ssl missing.
406 -h/--help This help text
407 -o/--output <file> Write result to file
408 -s/--ssl Make the request over HTTPS
409 -v Makes the operation more talkative
414 if __name__ == "__main__":
417 # check out our command line options
419 opt_list, arg_list = getopt.getopt(sys.argv[1:],
421 [ "output=", "verbose", \
422 "help","ssl","checkcert"])
429 for opt, arg in opt_list:
430 if opt in ("-h","--help"):
434 if opt in ("-c","--checkcert"):
437 if opt in ("-s","--ssl"):
440 if opt in ("-o","--output"):
446 if len(arg_list) != 1:
449 partialpath= arg_list[0]
450 if string.lower(partialpath[:4]) == "http":
457 # got the command line args straightened out
458 requestor= BootServerRequest(verbose)
461 requestor.DownloadFile( partialpath, None, None, ssl,
462 checkcert, output_file)
464 result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)