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 MONITORSERVER_CERTS= {}
47 # in seconds, how maximum time allowed for connect
48 DEFAULT_CURL_CONNECT_TIMEOUT=30
49 # in seconds, maximum time allowed for any transfer
50 DEFAULT_CURL_MAX_TRANSFER_TIME=3600
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
58 def __init__(self, vars, verbose=0):
63 # see if we have a boot cd mounted by checking for the version file
64 # if HAS_BOOTCD == 0 then either the machine doesn't have
65 # a boot cd, or something else is mounted
68 for path in self.CDROM_MOUNT_PATH:
69 self.Message( "Checking existance of boot cd on %s" % path )
71 os.system("/bin/mount %s > /dev/null 2>&1" % path )
73 version_file= self.VARS['BOOTCD_VERSION_FILE'] % {'path' : path}
74 self.Message( "Looking for version file %s" % version_file )
76 if os.access(version_file, os.R_OK) == 0:
77 self.Message( "No boot cd found." );
79 self.Message( "Found boot cd." )
85 # check the version of the boot cd, and locate the certs
86 self.Message( "Getting boot cd version." )
88 versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)")
90 bootcd_version_f= file(version_file,"r")
91 line= string.strip(bootcd_version_f.readline())
92 bootcd_version_f.close()
94 match= versionRegExp.findall(line)
96 (self.BOOTCD_VERSION)= match[0]
98 # right now, all the versions of the bootcd are supported,
99 # so no need to check it
101 self.Message( "Getting server from configuration" )
103 bootservers= [ self.VARS['BOOT_SERVER'] ]
104 for bootserver in bootservers:
105 bootserver = string.strip(bootserver)
106 cacert_path= "%s/%s/%s" % \
107 (self.VARS['SERVER_CERT_DIR'] % {'path' : path},
108 bootserver,self.VARS['CACERT_NAME'])
109 if os.access(cacert_path, os.R_OK):
110 self.BOOTSERVER_CERTS[bootserver]= cacert_path
112 monitorservers= [ self.VARS['MONITOR_SERVER'] ]
113 for monitorserver in monitorservers:
114 monitorserver = string.strip(monitorserver)
115 cacert_path= "%s/%s/%s" % \
116 (self.VARS['SERVER_CERT_DIR'] % {'path' : path},
117 monitorserver,self.VARS['CACERT_NAME'])
118 if os.access(cacert_path, os.R_OK):
119 self.MONITORSERVER_CERTS[monitorserver]= cacert_path
121 self.Message( "Set of servers to contact: %s" %
122 str(self.BOOTSERVER_CERTS) )
123 self.Message( "Set of servers to upload to: %s" %
124 str(self.MONITORSERVER_CERTS) )
126 self.Message( "Using default boot server address." )
127 self.BOOTSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']]= ""
128 self.MONITORSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']]= ""
131 def CheckProxy( self ):
132 # see if we have any proxy info from the machine
134 self.Message( "Checking existance of proxy config file..." )
136 if os.access(self.VARS['PROXY_FILE'], os.R_OK) and \
137 os.path.isfile(self.VARS['PROXY_FILE']):
138 self.PROXY= string.strip(file(self.VARS['PROXY_FILE'],'r').readline())
140 self.Message( "Using proxy %s." % self.PROXY)
142 self.Message( "Not using any proxy." )
146 def Message( self, Msg ):
152 def Error( self, Msg ):
153 sys.stderr.write( Msg + "\n" )
157 def Warning( self, Msg ):
162 def MakeRequest( self, PartialPath, GetVars,
163 PostVars, DoSSL, DoCertCheck,
164 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
165 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
168 (fd, buffer_name) = tempfile.mkstemp("MakeRequest-XXXXXX")
170 buffer = open(buffer_name, "w+b")
172 # the file "buffer_name" will be deleted by DownloadFile()
174 ok = self.DownloadFile(PartialPath, GetVars, PostVars,
175 DoSSL, DoCertCheck, buffer_name,
180 # check the ok code, return the string only if it was successfull
189 # just in case it is not deleted by DownloadFile()
190 os.unlink(buffer_name)
196 def DownloadFile(self, PartialPath, GetVars, PostVars,
197 DoSSL, DoCertCheck, DestFilePath,
198 ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT,
199 MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME,
202 self.Message( "Attempting to retrieve %s" % PartialPath )
204 # we can't do ssl and check the cert if we don't have a bootcd
205 if DoSSL and DoCertCheck and not self.HAS_BOOTCD:
206 self.Error( "No boot cd exists (needed to use -c and -s.\n" )
209 if DoSSL and not PYCURL_LOADED:
210 self.Warning( "Using SSL without pycurl will by default " \
211 "check at least standard certs." )
213 # ConnectTimeout has to be greater than 0
214 if ConnectTimeout <= 0:
215 self.Error( "Connect timeout must be greater than zero.\n" )
223 # setup the post and get vars for the request
226 postdata = urllib.urlencode(PostVars)
227 self.Message( "Posting data:\n%s\n" % postdata )
231 getstr= "?" + urllib.urlencode(GetVars)
232 self.Message( "Get data:\n%s\n" % getstr )
234 # now, attempt to make the request, starting at the first
237 cert_list = self.MONITORSERVER_CERTS
239 cert_list = self.BOOTSERVER_CERTS
241 for server in cert_list:
242 self.Message( "Contacting server %s." % server )
244 certpath = cert_list[server]
247 # output what we are going to be doing
248 self.Message( "Connect timeout is %s seconds" % \
251 self.Message( "Max transfer time is %s seconds" % \
255 url = "https://%s/%s%s" % (server,PartialPath,getstr)
257 if DoCertCheck and PYCURL_LOADED:
258 self.Message( "Using SSL version %d and verifying peer." %
259 self.CURL_SSL_VERSION )
261 self.Message( "Using SSL version %d." %
262 self.CURL_SSL_VERSION )
264 url = "http://%s/%s%s" % (server,PartialPath,getstr)
266 self.Message( "URL: %s" % url )
268 # setup a new pycurl instance, or a curl command line string
269 # if we don't have pycurl
274 # don't want curl sending any signals
275 curl.setopt(pycurl.NOSIGNAL, 1)
277 curl.setopt(pycurl.CONNECTTIMEOUT, ConnectTimeout)
278 curl.setopt(pycurl.TIMEOUT, MaxTransferTime)
280 # do not follow location when attempting to download a file
281 curl.setopt(pycurl.FOLLOWLOCATION, 0)
284 curl.setopt(pycurl.PROXY, self.PROXY )
287 curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION)
290 curl.setopt(pycurl.CAINFO, certpath)
291 curl.setopt(pycurl.SSL_VERIFYPEER, 2)
294 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
297 curl.setopt(pycurl.POSTFIELDS, postdata)
299 # setup multipart/form-data upload
301 curl.setopt(pycurl.HTTPPOST, FormData)
303 curl.setopt(pycurl.URL, url)
307 "--connect-timeout %d " \
309 "--header Pragma: " \
312 (self.CURL_CMD, ConnectTimeout,
313 MaxTransferTime, DestFilePath)
316 cmdline = cmdline + "--data '" + postdata + "' "
319 cmdline = cmdline + "".join(["--form '" + field + "' " for field in FormData])
322 cmdline = cmdline + "--silent "
325 cmdline = cmdline + "--proxy %s " % self.PROXY
328 cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION
330 cmdline = cmdline + "--cacert %s " % certpath
332 cmdline = cmdline + url
334 self.Message( "curl command: %s" % cmdline )
339 # setup the output file
340 outfile = open(DestFilePath,"wb")
342 self.Message( "Opened output file %s" % DestFilePath )
344 curl.setopt(pycurl.WRITEDATA, outfile)
346 self.Message( "Fetching..." )
348 self.Message( "Done." )
350 http_result= curl.getinfo(pycurl.HTTP_CODE)
354 self.Message( "Results saved in %s" % DestFilePath )
356 # check the code, return 1 if successfull
357 if http_result == self.HTTP_SUCCESS:
358 self.Message( "Successfull!" )
361 self.Message( "Failure, resultant http code: %d" % \
364 except pycurl.error, err:
366 self.Error( "connect to %s failed; curl error %d: '%s'\n" %
367 (server,errno,errstr) )
369 if not outfile.closed:
371 os.unlink(DestFilePath)
377 self.Message( "Fetching..." )
378 rc = os.system(cmdline)
379 self.Message( "Done." )
383 os.unlink( DestFilePath )
386 self.Message( "Failure, resultant curl code: %d" % rc )
387 self.Message( "Removed %s" % DestFilePath )
389 self.Message( "Successfull!" )
392 self.Error( "Unable to successfully contact any boot servers.\n" )
401 Usage: BootServerRequest.py [options] <partialpath>
403 -c/--checkcert Check SSL certs. Ignored if -s/--ssl missing.
404 -h/--help This help text
405 -o/--output <file> Write result to file
406 -s/--ssl Make the request over HTTPS
407 -v Makes the operation more talkative
412 if __name__ == "__main__":
415 # check out our command line options
417 opt_list, arg_list = getopt.getopt(sys.argv[1:],
419 [ "output=", "verbose", \
420 "help","ssl","checkcert"])
427 for opt, arg in opt_list:
428 if opt in ("-h","--help"):
432 if opt in ("-c","--checkcert"):
435 if opt in ("-s","--ssl"):
438 if opt in ("-o","--output"):
444 if len(arg_list) != 1:
447 partialpath= arg_list[0]
448 if string.lower(partialpath[:4]) == "http":
455 # got the command line args straightened out
456 requestor= BootServerRequest(verbose)
459 requestor.DownloadFile( partialpath, None, None, ssl,
460 checkcert, output_file)
462 result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert)