No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

servefile 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # Licensed under GNU General Public License v3 or later
  4. # Written by Sebastian Lohff (seba@seba-geek.de)
  5. # http://seba-geek.de/stuff/servefile/
  6. from __future__ import print_function
  7. __version__ = '0.4.2'
  8. import argparse
  9. import base64
  10. import cgi
  11. import datetime
  12. import mimetypes
  13. import urllib
  14. import os
  15. import posixpath
  16. import re
  17. import select
  18. import socket
  19. from subprocess import Popen, PIPE
  20. import sys
  21. import time
  22. # fix imports for python2/python3
  23. try:
  24. import BaseHTTPServer
  25. import SocketServer
  26. except ImportError:
  27. # both have different names in python3
  28. import http.server as BaseHTTPServer
  29. import socketserver as SocketServer
  30. # only activate SSL if available
  31. HAVE_SSL = False
  32. try:
  33. from OpenSSL import SSL, crypto
  34. HAVE_SSL = True
  35. except ImportError:
  36. pass
  37. def getDateStrNow():
  38. """ Get the current time formatted for HTTP header """
  39. now = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
  40. return now.strftime("%a, %d %b %Y %H:%M:%S GMT")
  41. class FileBaseHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  42. fileName = None
  43. blockSize = 1024 * 1024
  44. server_version = "servefile/" + __version__
  45. def checkAndDoRedirect(self, fileName=None):
  46. """ If request didn't request self.fileName redirect to self.fileName.
  47. Returns True if a redirect was issued. """
  48. if not fileName:
  49. fileName = self.fileName
  50. if urllib.unquote(self.path) != "/" + fileName:
  51. self.send_response(302)
  52. self.send_header('Location', '/' + fileName)
  53. self.end_headers()
  54. return True
  55. return False
  56. def sendContentHeaders(self, fileName, fileLength, lastModified=None):
  57. """ Send default Content headers for given fileName and fileLength.
  58. If no lastModified is given the current date is taken. If
  59. fileLength is lesser than 0 no Content-Length will be sent."""
  60. if not lastModified:
  61. lastModified = getDateStrNow()
  62. if fileLength >= 0:
  63. self.send_header('Content-Length', str(fileLength))
  64. self.send_header('Last-Modified', lastModified)
  65. self.send_header('Content-Type', 'application/octet-stream')
  66. self.send_header('Content-Disposition', 'attachment; filename="%s"' % fileName)
  67. self.send_header('Content-Transfer-Encoding', 'binary')
  68. def isRangeRequest(self):
  69. """ Return True if partial content is requestet """
  70. return "Range" in self.headers
  71. def handleRangeRequest(self, fileLength):
  72. """ Find out and handle continuing downloads.
  73. Returns a tuple of a boolean, if this is a valid range request,
  74. and a range. When the requested range is out of range, range is
  75. set to None.
  76. """
  77. fromto = None
  78. if self.isRangeRequest():
  79. cont = self.headers.get("Range").split("=")
  80. if len(cont) > 1 and cont[0] == 'bytes':
  81. fromto = cont[1].split('-')
  82. if len(fromto) > 1:
  83. if fromto[1] == '':
  84. fromto[1] = fileLength - 1
  85. try:
  86. fromto[0] = int(fromto[0])
  87. fromto[1] = int(fromto[1])
  88. except:
  89. return (False, None)
  90. if fromto[0] >= fileLength or fromto[0] < 0 or fromto[1] >= fileLength or fromto[1]-fromto[0] < 0:
  91. # oops, already done! (requested range out of range)
  92. self.send_response(416)
  93. self.send_header('Content-Range', 'bytes */%d' % fileLength)
  94. self.end_headers()
  95. return (True, None)
  96. return (True, fromto)
  97. # broken request or no range header
  98. return (False, None)
  99. def sendFile(self, filePath, fileLength=None, lastModified=None):
  100. """ Send file with continuation support.
  101. filePath: path to file to be sent
  102. fileLength: length of file (if None is given this will be found out)
  103. lastModified: time the file was last modified, None for "now"
  104. """
  105. if not fileLength:
  106. fileLength = os.stat(filePath).st_size
  107. (responseCode, myfile) = self.getFileHandle(filePath)
  108. if not myfile:
  109. self.send_response(responseCode)
  110. self.end_headers()
  111. return
  112. (continueDownload, fromto) = self.handleRangeRequest(fileLength)
  113. if continueDownload:
  114. if not fromto:
  115. # we are done
  116. return True
  117. # now we can wind the file *brrrrrr*
  118. myfile.seek(fromto[0])
  119. if fromto != None:
  120. self.send_response(216)
  121. self.send_header('Content-Range', 'bytes %d-%d/%d' % (fromto[0], fromto[1], fileLength))
  122. fileLength = fromto[1] - fromto[0] + 1
  123. else:
  124. self.send_response(200)
  125. fileName = self.fileName
  126. if not fileName:
  127. fileName = os.path.basename(filePath)
  128. self.sendContentHeaders(fileName, fileLength, lastModified)
  129. self.end_headers()
  130. block = self.getChunk(myfile, fromto)
  131. while block:
  132. try:
  133. self.wfile.write(block)
  134. except socket.error as e:
  135. print("%s ABORTED transmission (Reason %s: %s)" % (self.client_address[0], e[0], e[1]))
  136. return False
  137. block = self.getChunk(myfile, fromto)
  138. myfile.close()
  139. print("%s finished downloading %s" % (self.client_address[0], filePath))
  140. return True
  141. def getChunk(self, myfile, fromto):
  142. if fromto and myfile.tell()+self.blockSize >= fromto[1]:
  143. readsize = fromto[1]-myfile.tell()+1
  144. else:
  145. readsize = self.blockSize
  146. return myfile.read(readsize)
  147. def getFileHandle(self, path):
  148. """ Get handle to a file.
  149. Return a tuple of HTTP response code and file handle.
  150. If the handle couldn't be acquired it is set to None
  151. and an appropriate HTTP error code is returned.
  152. """
  153. myfile = None
  154. responseCode = 200
  155. try:
  156. myfile = open(path, 'rb')
  157. except IOError as e:
  158. responseCode = self.getResponseForErrno(e.errno)
  159. return (responseCode, myfile)
  160. def getFileLength(self, path):
  161. """ Get length of a file.
  162. Return a tuple of HTTP response code and file length.
  163. If filelength couldn't be determined, it is set to -1
  164. and an appropriate HTTP error code is returned.
  165. """
  166. fileSize = -1
  167. responseCode = 200
  168. try:
  169. fileSize = os.stat(path).st_size
  170. except IOError as e:
  171. responseCode = self.getResponseForErrno(e.errno)
  172. return (responseCode, fileSize)
  173. def getResponseForErrno(self, errno):
  174. """ Return HTTP response code for an IOError errno """
  175. if errno == errno.ENOENT:
  176. return 404
  177. elif errno == errno.EACCESS:
  178. return 403
  179. else:
  180. return 500
  181. class FileHandler(FileBaseHandler):
  182. filePath = "/dev/null"
  183. fileLength = 0
  184. startTime = getDateStrNow()
  185. def do_HEAD(self):
  186. if self.checkAndDoRedirect():
  187. return
  188. self.send_response(200)
  189. self.sendContentHeaders(self.fileName, self.fileLength, self.startTime)
  190. self.end_headers()
  191. def do_GET(self):
  192. if self.checkAndDoRedirect():
  193. return
  194. self.sendFile(self.filePath, self.fileLength, self.startTime)
  195. class TarFileHandler(FileBaseHandler):
  196. target = None
  197. compression = "none"
  198. compressionMethods = ("none", "gzip", "bzip2")
  199. def do_HEAD(self):
  200. if self.checkAndDoRedirect():
  201. return
  202. self.send_response(200)
  203. self.sendContentHeaders(self.fileName, -1)
  204. self.end_headers()
  205. def do_GET(self):
  206. if self.checkAndDoRedirect():
  207. return
  208. tarCmd = Popen(self.getCompressionCmd(), stdout=PIPE)
  209. # give the process a short time to find out if it can
  210. # pack/compress the file
  211. time.sleep(0.05)
  212. if tarCmd.poll() != None and tarCmd.poll() != 0:
  213. # something went wrong
  214. print("Error while compressing '%s'. Aborting request." % self.target)
  215. self.send_response(500)
  216. self.end_headers()
  217. return
  218. self.send_response(200)
  219. self.sendContentHeaders(self.fileName, -1)
  220. self.end_headers()
  221. block = True
  222. while block and block != '':
  223. block = tarCmd.stdout.read(self.blockSize)
  224. if block and block != '':
  225. self.wfile.write(block)
  226. print("%s finished downloading" % (self.client_address[0]))
  227. def getCompressionCmd(self):
  228. if self.compression == "none":
  229. cmd = ["tar", "-c"]
  230. elif self.compression == "gzip":
  231. cmd = ["tar", "-cz"]
  232. elif self.compression == "bzip2":
  233. cmd = ["tar", "-cj"]
  234. else:
  235. raise ValueError("Unknown compression mode '%s'." % self.compression)
  236. dirname = os.path.basename(self.target.rstrip("/"))
  237. chdirTo = os.path.dirname(self.target.rstrip("/"))
  238. if chdirTo != '':
  239. cmd.extend(["-C", chdirTo])
  240. cmd.append(dirname)
  241. return cmd
  242. @staticmethod
  243. def getCompressionExt():
  244. if TarFileHandler.compression == "none":
  245. return ".tar"
  246. elif TarFileHandler.compression == "gzip":
  247. return ".tar.gz"
  248. elif TarFileHandler.compression == "bzip2":
  249. return ".tar.bz2"
  250. raise ValueError("Unknown compression mode '%s'." % TarFileHandler.compression)
  251. class DirListingHandler(FileBaseHandler):
  252. """ DOCUMENTATION MISSING """
  253. targetDir = None
  254. def do_HEAD(self):
  255. self.getFileOrDirectory(head=True)
  256. def do_GET(self):
  257. self.getFileOrDirectory(head=False)
  258. def getFileOrDirectory(self, head=False):
  259. """ Send file or directory index, depending on requested path """
  260. path = self.getCleanPath()
  261. if os.path.isdir(path):
  262. if not self.path.endswith('/'):
  263. self.send_response(301)
  264. self.send_header("Location", self.path + '/')
  265. self.end_headers()
  266. else:
  267. self.sendDirectoryListing(path, head)
  268. elif os.path.isfile(path):
  269. if head:
  270. (response, length) = self.getFileLength(path)
  271. if length < 0:
  272. self.send_response(response)
  273. self.end_headers()
  274. else:
  275. self.send_response(200)
  276. self.sendContentHeaders(self, path, length)
  277. self.end_headers()
  278. else:
  279. self.sendFile(path, head)
  280. else:
  281. self.send_response(404)
  282. errorMsg = """<!DOCTYPE html><html>
  283. <head><title>404 Not Found</title></head>
  284. <body>
  285. <h1>Not Found</h1>
  286. <p>The requestet URL %s was not found on this server</p>
  287. <p><a href="/">Back to /</a>
  288. </body>
  289. </html>""" % self.escapeHTML(urllib.unquote(self.path))
  290. self.send_header("Content-Length", str(len(errorMsg)))
  291. self.end_headers()
  292. if not head:
  293. self.wfile.write(errorMsg)
  294. def escapeHTML(self, htmlstr):
  295. entities = [("<", "&lt;"), (">", "&gt;")]
  296. for src, dst in entities:
  297. htmlstr = htmlstr.replace(src, dst)
  298. return htmlstr
  299. def sendDirectoryListing(self, path, head):
  300. """ Generate a directorylisting for path and send it """
  301. header = """<!DOCTYPE html>
  302. <html>
  303. <head>
  304. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  305. <title>Index of %(path)s</title>
  306. <style type="text/css">
  307. a { text-decoration: none; color: #0000BB;}
  308. a:visited { color: #000066;}
  309. a:hover, a:focus, a:active { text-decoration: underline; color: #cc0000; text-indent: 5px; }
  310. body { background-color: #eaeaea; padding: 20px 0; margin: 0; font: 400 13px/1.2em Arial, sans-serif; }
  311. h1 { margin: 0 10px 12px 10px; font-family: Arial, sans-serif; }
  312. div.content { background-color: white; border-color: #ccc; border-width: 1px 0; border-style: solid; padding: 10px 10px 15px 10px; }
  313. td { padding-right: 15px; text-align: left; font-family: monospace; }
  314. th { font-weight: bold; font-size: 115%%; padding: 0 15px 5px 0; text-align: left; }
  315. .size { text-align: right; }
  316. .footer { font: 12px monospace; color: #333; margin: 5px 10px 0; }
  317. .footer, h1 { text-shadow: 0 1px 0 white; }
  318. </style>
  319. </head>
  320. <body>
  321. <h1>Index of %(path)s</h1>
  322. <div class="content">
  323. <table summary="Directory Listing">
  324. <thead>
  325. <tr>
  326. <th class="name">Name</th>
  327. <th class="lastModified">Last Modified</th>
  328. <th class="size">Size</th>
  329. <th class="type">Type</th>
  330. </tr>
  331. </thead>
  332. <tbody>
  333. """ % {'path': posixpath.normpath(urllib.unquote(self.path))}
  334. footer = """</tbody></table></div>
  335. <div class="footer"><a href="http://seba-geek.de/stuff/servefile/">servefile %(version)s</a></div>
  336. </body>
  337. </html>""" % {'version': __version__}
  338. content = []
  339. for item in [".."] + sorted(os.listdir(path)):
  340. # create path to item
  341. itemPath = os.path.join(path, item)
  342. # try to stat file for size, last modified... continue on error
  343. stat = None
  344. try:
  345. stat = os.stat(itemPath)
  346. except IOError:
  347. continue
  348. # Strings to display on directory listing
  349. lastModifiedDate = datetime.datetime.fromtimestamp(stat.st_mtime)
  350. lastModified = lastModifiedDate.strftime("%Y-%m-%d %H:%M")
  351. fileSize = "%.1f%s" % self.convertSize(stat.st_size)
  352. (fileType, _) = mimetypes.guess_type(itemPath)
  353. if not fileType:
  354. fileType = "-"
  355. if os.path.isdir(itemPath):
  356. item += "/"
  357. fileType = "Directory"
  358. content.append("""
  359. <tr>
  360. <td class="name"><a href="%s">%s</a></td>
  361. <td class="last-modified">%s</td>
  362. <td class="size">%s</td>
  363. <td class="type">%s</td>
  364. </tr>""" % (urllib.quote(item), item, lastModified, fileSize, fileType))
  365. listing = header + "\n".join(content) + footer
  366. # write listing
  367. self.send_response(200)
  368. self.send_header("Content-Type", "text/html")
  369. if head:
  370. self.end_headers()
  371. return
  372. self.send_header("Content-Length", str(len(listing)))
  373. self.end_headers()
  374. self.wfile.write(listing)
  375. def convertSize(self, size):
  376. for ext in "KMGT":
  377. size /= 1024.0
  378. if size < 1024.0:
  379. break
  380. if ext == "K" and size < 0.1:
  381. size = 0.1
  382. return (size, ext.strip())
  383. def getCleanPath(self):
  384. urlPath = posixpath.normpath(urllib.unquote(self.path)).strip("/")
  385. path = os.path.join(self.targetDir, urlPath)
  386. return path
  387. class FilePutter(BaseHTTPServer.BaseHTTPRequestHandler):
  388. """ Simple HTTP Server which allows uploading to a specified directory
  389. either via multipart/form-data or POST/PUT requests containing the file.
  390. """
  391. targetDir = None
  392. maxUploadSize = 0
  393. blockSize = 1024 * 1024
  394. uploadPage = """
  395. <!docype html>
  396. <html>
  397. <form action="/" method="post" enctype="multipart/form-data">
  398. <label for="file">Filename:</label>
  399. <input type="file" name="file" id="file" />
  400. <br />
  401. <input type="submit" name="submit" value="Upload" />
  402. </form>
  403. </html>
  404. """
  405. def do_GET(self):
  406. """ Answer every GET request with the upload form """
  407. self.sendResponse(200, self.uploadPage)
  408. def do_POST(self):
  409. """ Upload a file via POST
  410. If the content-type is multipart/form-data it checks for the file
  411. field and saves the data to disk. For other content-types it just
  412. calls do_PUT and is handled as such except for the http response code.
  413. Files can be uploaded with wget --post-file=path/to/file <url> or
  414. curl -X POST -d @file <url> .
  415. """
  416. length = self.getContentLength()
  417. if length < 0:
  418. return
  419. ctype = self.headers.getheader('Content-Type')
  420. # check for multipart/form-data.
  421. if not (ctype and ctype.lower().startswith("multipart/form-data")):
  422. # not a normal multipart request ==> handle as PUT request
  423. return self.do_PUT(fromPost=True)
  424. # create FieldStorage object for multipart parsing
  425. env = os.environ
  426. env['REQUEST_METHOD'] = "POST"
  427. fstorage = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ=env)
  428. if not "file" in fstorage:
  429. self.sendResponse(400, "No file found in request.")
  430. return
  431. destFileName = self.getTargetName(fstorage["file"].filename)
  432. if destFileName == "":
  433. self.sendResponse(400, "Filename was empty or invalid")
  434. return
  435. # write file down to disk, send a 200 afterwards
  436. target = open(destFileName, "w")
  437. bytesLeft = length
  438. while bytesLeft > 0:
  439. bytesToRead = min(self.blockSize, bytesLeft)
  440. target.write(fstorage["file"].file.read(bytesToRead))
  441. bytesLeft -= bytesToRead
  442. target.close()
  443. self.sendResponse(200, "OK! Thanks for uploading")
  444. print("Received file '%s' from %s." % (destFileName, self.client_address[0]))
  445. def do_PUT(self, fromPost=False):
  446. """ Upload a file via PUT
  447. The request path is used as filename, so uploading a file to the url
  448. http://host:8080/testfile will cause the file to be named testfile. If
  449. no filename is given, a random name will be generated.
  450. Files can be uploaded with e.g. curl -X POST -d @file <url> .
  451. """
  452. length = self.getContentLength()
  453. if length < 0:
  454. return
  455. fileName = urllib.unquote(self.path)
  456. if fileName == "/":
  457. # if no filename was given we have to generate one
  458. fileName = str(time.time())
  459. cleanFileName = self.getTargetName(fileName)
  460. if cleanFileName == "":
  461. self.sendResponse(400, "Filename was invalid")
  462. return
  463. # Sometimes clients want to be told to continue with their transfer
  464. if self.headers.getheader("Expect") == "100-continue":
  465. self.send_response(100)
  466. self.end_headers()
  467. target = open(cleanFileName, "w")
  468. bytesLeft = int(self.headers['Content-Length'])
  469. while bytesLeft > 0:
  470. bytesToRead = min(self.blockSize, bytesLeft)
  471. target.write(self.rfile.read(bytesToRead))
  472. bytesLeft -= bytesToRead
  473. target.close()
  474. self.sendResponse(200 if fromPost else 201, "OK!")
  475. def getContentLength(self):
  476. length = 0
  477. try:
  478. length = int(self.headers['Content-Length'])
  479. except (ValueError, KeyError):
  480. pass
  481. if length <= 0:
  482. self.sendResponse(411, "Content-Length was invalid or not set.")
  483. return -1
  484. if self.maxUploadSize > 0 and length > self.maxUploadSize:
  485. self.sendResponse(413, "Your file was too big! Maximum allowed size is %d byte. <a href=\"/\">back</a>" % self.maxUploadSize)
  486. return -1
  487. return length
  488. def sendResponse(self, code, msg):
  489. """ Send a HTTP response with HTTP statuscode code and message msg,
  490. providing the correct content-length.
  491. """
  492. self.send_response(code)
  493. self.send_header('Content-Type', 'text/html')
  494. self.send_header('Content-Length', str(len(msg)))
  495. self.end_headers()
  496. self.wfile.write(msg)
  497. def getTargetName(self, fname):
  498. """ Generate a clean and secure filename.
  499. This function takes a filename and strips all the slashes out of it.
  500. If the file already exists in the target directory, a (NUM) will be
  501. appended, so no file will be overwritten.
  502. """
  503. cleanFileName = fname.replace("/", "")
  504. if cleanFileName == "":
  505. return ""
  506. destFileName = os.path.join(self.targetDir, cleanFileName)
  507. if not os.path.exists(destFileName):
  508. return destFileName
  509. else:
  510. i = 1
  511. extraDestFileName = destFileName + "(%s)" % i
  512. while os.path.exists(extraDestFileName):
  513. i += 1
  514. extraDestFileName = destFileName + "(%s)" % i
  515. return extraDestFileName
  516. # never reached
  517. class ThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
  518. pass
  519. def catchSSLErrors(BaseSSLClass):
  520. """ Class decorator which catches SSL errors and prints them. """
  521. class X(BaseSSLClass):
  522. def handle_one_request(self, *args, **kwargs):
  523. try:
  524. BaseSSLClass.handle_one_request(self, *args, **kwargs)
  525. except SSL.Error as e:
  526. if str(e) == "":
  527. print("%s SSL error (empty error message)" % (self.client_address[0],))
  528. else:
  529. print("%s SSL error: %s" % (self.client_address[0], e))
  530. return X
  531. class SecureThreadedHTTPServer(ThreadedHTTPServer):
  532. def __init__(self, pubKey, privKey, server_address, RequestHandlerClass, bind_and_activate=True):
  533. ThreadedHTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
  534. ctx = SSL.Context(SSL.SSLv23_METHOD)
  535. if type(pubKey) is crypto.X509 and type(privKey) is crypto.PKey:
  536. ctx.use_certificate(pubKey)
  537. ctx.use_privatekey(privKey)
  538. else:
  539. ctx.use_certificate_file(pubKey)
  540. ctx.use_privatekey_file(privKey)
  541. self.bsocket = socket.socket(self.address_family, self.socket_type)
  542. self.socket = SSL.Connection(ctx, self.bsocket)
  543. if bind_and_activate:
  544. self.server_bind()
  545. self.server_activate()
  546. def shutdown_request(self, request):
  547. request.shutdown()
  548. class SecureHandler():
  549. def setup(self):
  550. self.connection = self.request
  551. self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
  552. self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
  553. class ServeFileException(Exception):
  554. pass
  555. class ServeFile():
  556. """ Main class to manage everything. """
  557. _NUM_MODES = 4
  558. (MODE_SINGLE, MODE_SINGLETAR, MODE_UPLOAD, MODE_LISTDIR) = range(_NUM_MODES)
  559. def __init__(self, target, port=8080, serveMode=0, useSSL=False):
  560. self.target = target
  561. self.port = port
  562. self.serveMode = serveMode
  563. self.dirCreated = False
  564. self.useSSL = useSSL
  565. self.cert = self.key = None
  566. self.auth = None
  567. self.maxUploadSize = 0
  568. self.listenIPv4 = True
  569. self.listenIPv6 = True
  570. if self.serveMode not in range(self._NUM_MODES):
  571. self.serveMode = None
  572. raise ValueError("Unknown serve mode, needs to be MODE_SINGLE, MODE_SINGLETAR, MODE_UPLOAD or MODE_DIRLIST.")
  573. def setIPv4(self, ipv4):
  574. """ En- or disable ipv4 """
  575. self.listenIPv4 = ipv4
  576. def setIPv6(self, ipv6):
  577. """ En- or disable ipv6 """
  578. self.listenIPv6 = ipv6
  579. def getIPs(self):
  580. """ Get IPs from all interfaces via ip or ifconfig. """
  581. # ip and ifconfig sometimes are located in /sbin/
  582. os.environ['PATH'] += ':/sbin:/usr/sbin'
  583. proc = Popen(r"ip addr|" + \
  584. "sed -n -e 's/.*inet6\{0,1\} \([0-9.a-fA-F:]\+\).*/\\1/ p'|" + \
  585. "grep -v '^fe80\|^127.0.0.1\|^::1'", \
  586. shell=True, stdout=PIPE, stderr=PIPE)
  587. if proc.wait() != 0:
  588. # ip failed somehow, falling back to ifconfig
  589. oldLang = os.environ.get("LC_ALL", None)
  590. os.environ['LC_ALL'] = "C"
  591. proc = Popen(r"ifconfig|" + \
  592. "sed -n 's/.*inet6\{0,1\}\( addr:\)\{0,1\} \{0,1\}\([0-9a-fA-F.:]*\).*/" + \
  593. "\\2/p'|" + \
  594. "grep -v '^fe80\|^127.0.0.1\|^::1'", \
  595. shell=True, stdout=PIPE, stderr=PIPE)
  596. if oldLang:
  597. os.environ['LC_ALL'] = oldLang
  598. else:
  599. del(os.environ['LC_ALL'])
  600. if proc.wait() != 0:
  601. # we couldn't find any ip address
  602. proc = None
  603. if proc:
  604. ips = proc.stdout.read().strip().split("\n")
  605. # filter out ips we are not listening on
  606. if not self.listenIPv6:
  607. ips = filter(lambda ip: ":" not in ip, ips)
  608. if not self.listenIPv4:
  609. ips = filter(lambda ip: "." not in ip, ips)
  610. return ips
  611. return None
  612. def setSSLKeys(self, cert, key):
  613. """ Set SSL cert/key. Can be either path to file or pyssl X509/PKey object. """
  614. self.cert = cert
  615. self.key = key
  616. def setMaxUploadSize(self, limit):
  617. """ Set the maximum upload size in byte """
  618. self.maxUploadSize = limit
  619. def setCompression(self, compression):
  620. """ Set the compression of TarFileHandler """
  621. if self.serveMode != self.MODE_SINGLETAR:
  622. raise ServeFileException("Compression mode can only be set in tar-mode.")
  623. if compression not in TarFileHandler.compressionMethods:
  624. raise ServeFileException("Compression mode not available.")
  625. TarFileHandler.compression = compression
  626. def genKeyPair(self):
  627. print("Generating SSL certificate...", end="")
  628. sys.stdout.flush()
  629. pkey = crypto.PKey()
  630. pkey.generate_key(crypto.TYPE_RSA, 2048)
  631. req = crypto.X509Req()
  632. subj = req.get_subject()
  633. subj.CN = "127.0.0.1"
  634. subj.O = "servefile laboratories"
  635. subj.OU = "servefile"
  636. # generate altnames
  637. altNames = []
  638. for ip in self.getIPs() + ["127.0.0.1", "::1"]:
  639. altNames.append("IP:%s" % ip)
  640. altNames.append("DNS:localhost")
  641. ext = crypto.X509Extension("subjectAltName", False, ",".join(altNames))
  642. req.add_extensions([ext])
  643. req.set_pubkey(pkey)
  644. req.sign(pkey, "sha1")
  645. cert = crypto.X509()
  646. # some browsers complain if they see a cert from the same authority
  647. # with the same serial ==> we just use the seconds as serial.
  648. cert.set_serial_number(int(time.time()))
  649. cert.gmtime_adj_notBefore(0)
  650. cert.gmtime_adj_notAfter(365*24*60*60)
  651. cert.set_issuer(req.get_subject())
  652. cert.set_subject(req.get_subject())
  653. cert.add_extensions([ext])
  654. cert.set_pubkey(req.get_pubkey())
  655. cert.sign(pkey, "sha1")
  656. self.cert = cert
  657. self.key = pkey
  658. print("done.")
  659. print("SHA1 fingerprint:", cert.digest("sha1"))
  660. print("MD5 fingerprint:", cert.digest("md5"))
  661. def _getCert(self):
  662. return self.cert
  663. def _getKey(self):
  664. return self.key
  665. def setAuth(self, user, password, realm=None):
  666. if not user or not password:
  667. raise ServeFileException("User and password both need to be at least one character.")
  668. self.auth = base64.b64encode("%s:%s" % (user, password))
  669. self.authrealm = realm
  670. def _createServer(self, handler, withv6=False):
  671. ThreadedHTTPServer.address_family = socket.AF_INET
  672. SecureThreadedHTTPServer.address_family = socket.AF_INET
  673. listenIp = ''
  674. server = None
  675. if withv6:
  676. listenIp = '::'
  677. ThreadedHTTPServer.address_family = socket.AF_INET6
  678. SecureThreadedHTTPServer.address_family = socket.AF_INET6
  679. if self.useSSL:
  680. if not self._getKey():
  681. self.genKeyPair()
  682. try:
  683. server = SecureThreadedHTTPServer(self._getCert(), self._getKey(),
  684. (listenIp, self.port), handler, bind_and_activate=False)
  685. except SSL.Error as e:
  686. raise ServeFileException("SSL error: Could not read SSL public/private key from file(s) (error was: \"%s\")" % (e[0][0][2],))
  687. else:
  688. server = ThreadedHTTPServer((listenIp, self.port), handler,
  689. bind_and_activate=False)
  690. if withv6:
  691. server.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  692. server.server_bind()
  693. server.server_activate()
  694. return server
  695. def serve(self):
  696. self.handler = self._confAndFindHandler()
  697. self.server = []
  698. try:
  699. currsocktype = "IPv4"
  700. if self.listenIPv4:
  701. self.server.append(self._createServer(self.handler))
  702. currsocktype = "IPv6"
  703. if self.listenIPv6:
  704. self.server.append(self._createServer(self.handler, withv6=True))
  705. except socket.error as e:
  706. raise ServeFileException("Could not open %s socket: %s" % (currsocktype, e))
  707. if self.serveMode != self.MODE_UPLOAD:
  708. print("Serving \"%s\" at port %d." % (self.target, self.port))
  709. else:
  710. print("Serving \"%s\" for uploads at port %d." % (self.target, self.port))
  711. # print urls with local network adresses
  712. print("\nSome addresses %s will be available at:" % \
  713. ("this file" if (self.serveMode != self.MODE_UPLOAD) else "the uploadform", ))
  714. ips = self.getIPs()
  715. if not ips or len(ips) == 0 or ips[0] == '':
  716. print("Could not find any addresses.")
  717. else:
  718. for ip in ips:
  719. if ":" in ip:
  720. ip = "[%s]" % ip
  721. print("\thttp%s://%s:%d/" % (self.useSSL and "s" or "", ip, self.port))
  722. print()
  723. try:
  724. while True:
  725. (servers, _, _) = select.select(self.server, [], [])
  726. for server in servers:
  727. server.handle_request()
  728. except KeyboardInterrupt:
  729. for server in self.server:
  730. server.socket.close()
  731. # cleanup potential upload directory
  732. if self.dirCreated and len(os.listdir(self.target)) == 0:
  733. # created upload dir was not used
  734. os.rmdir(self.target)
  735. def _confAndFindHandler(self):
  736. handler = None
  737. if self.serveMode == self.MODE_SINGLE:
  738. try:
  739. testit = open(self.target, 'r')
  740. testit.close()
  741. except IOError:
  742. raise ServeFileException("Error: Could not open file!")
  743. FileHandler.filePath = self.target
  744. FileHandler.fileName = os.path.basename(self.target)
  745. FileHandler.fileLength = os.stat(self.target).st_size
  746. handler = FileHandler
  747. elif self.serveMode == self.MODE_SINGLETAR:
  748. self.realTarget = os.path.realpath(self.target)
  749. if not os.path.exists(self.realTarget):
  750. raise ServeFileException("Error: Could not open file or directory.")
  751. TarFileHandler.target = self.realTarget
  752. TarFileHandler.fileName = os.path.basename(self.realTarget.rstrip("/")) + TarFileHandler.getCompressionExt()
  753. handler = TarFileHandler
  754. elif self.serveMode == self.MODE_UPLOAD:
  755. if os.path.isdir(self.target):
  756. print("Warning: Uploading to an already existing directory.")
  757. elif not os.path.exists(self.target):
  758. self.dirCreated = True
  759. try:
  760. os.mkdir(self.target)
  761. except (IOError, OSError):
  762. raise ServeFileException("Error: Could not create directory '%s' for uploads." % (self.target,))
  763. else:
  764. raise ServeFileException("Error: Upload directory already exists and is a file.")
  765. FilePutter.targetDir = self.target
  766. FilePutter.maxUploadSize = self.maxUploadSize
  767. handler = FilePutter
  768. elif self.serveMode == self.MODE_LISTDIR:
  769. if not os.path.exists(self.target):
  770. raise ServeFileException("Error: Could not open file or directory.")
  771. if not os.path.isdir(self.target):
  772. raise ServeFileException("Error: '%s' is not a directory." % (self.target,))
  773. handler = DirListingHandler
  774. handler.targetDir = self.target
  775. if self.auth:
  776. # do authentication
  777. AuthenticationHandler.authString = self.auth
  778. if self.authrealm:
  779. AuthenticationHandler.realm = self.authrealm
  780. class AuthenticatedHandler(AuthenticationHandler, handler):
  781. pass
  782. handler = AuthenticatedHandler
  783. if self.useSSL:
  784. # secure handler
  785. @catchSSLErrors
  786. class AlreadySecuredHandler(SecureHandler, handler):
  787. pass
  788. handler = AlreadySecuredHandler
  789. return handler
  790. class AuthenticationHandler():
  791. # base64 encoded user:password string for authentication
  792. authString = None
  793. realm = "Restricted area"
  794. def handle_one_request(self):
  795. """ Overloaded function to handle one request.
  796. Before calling the responsible do_METHOD function, check credentials
  797. """
  798. self.raw_requestline = self.rfile.readline()
  799. if not self.raw_requestline:
  800. self.close_connection = 1
  801. return
  802. if not self.parse_request(): # An error code has been sent, just exit
  803. return
  804. authorized = False
  805. if "Authorization" in self.headers:
  806. if self.headers["Authorization"] == ("Basic " + self.authString):
  807. authorized = True
  808. if authorized:
  809. mname = 'do_' + self.command
  810. if not hasattr(self, mname):
  811. self.send_error(501, "Unsupported method (%r)" % self.command)
  812. return
  813. method = getattr(self, mname)
  814. method()
  815. else:
  816. self.send_response(401)
  817. self.send_header("WWW-Authenticate", "Basic realm=\"%s\"" % self.realm)
  818. def main():
  819. parser = argparse.ArgumentParser(description='Serve a single file via HTTP.')
  820. parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
  821. parser.add_argument('target', metavar='file/directory', type=str)
  822. parser.add_argument('-p', '--port', type=int, default=8080, \
  823. help='Port to listen on')
  824. parser.add_argument('-u', '--upload', action="store_true", default=False, \
  825. help="Enable uploads to a given directory")
  826. parser.add_argument('-s', '--max-upload-size', type=str, \
  827. help="Limit upload size in kB. Size modifiers are allowed, e.g. 2G, 12MB, 1B")
  828. parser.add_argument('-l', '--list-dir', action="store_true", default=False, \
  829. help="Show directory indexes and allow access to all subdirectories")
  830. parser.add_argument('--ssl', action="store_true", default=False, \
  831. help="Enable SSL. If no key/cert is specified one will be generated")
  832. parser.add_argument('--key', type=str, \
  833. help="Keyfile to use for SSL. If no cert is given with --cert the keyfile will also be searched for a cert")
  834. parser.add_argument('--cert', type=str, \
  835. help="Certfile to use for SSL")
  836. parser.add_argument('-a', '--auth', type=str, metavar='user:password', \
  837. help="Set user and password for HTTP basic authentication")
  838. parser.add_argument('--realm', type=str, default=None,\
  839. help="Set a realm for HTTP basic authentication")
  840. parser.add_argument('-t', '--tar', action="store_true", default=False, \
  841. help="Enable on the fly tar creation for given file or directory. Note: Download continuation will not be available")
  842. parser.add_argument('-c', '--compression', type=str, metavar='method', \
  843. default="none", \
  844. help="Set compression method, only in combination with --tar. Can be one of %s" % ", ".join(TarFileHandler.compressionMethods))
  845. parser.add_argument('-4', '--ipv4-only', action="store_true", default=False, \
  846. help="Listen on IPv4 only")
  847. parser.add_argument('-6', '--ipv6-only', action="store_true", default=False, \
  848. help="Listen on IPv6 only")
  849. args = parser.parse_args()
  850. maxUploadSize = 0
  851. # check for invalid option combinations/preparse stuff
  852. if args.max_upload_size and not args.upload:
  853. print("Error: Maximum upload size can only be specified when in upload mode.")
  854. sys.exit(1)
  855. if args.upload and args.list_dir:
  856. print("Error: Upload and dirlisting can't be enabled together.")
  857. sys.exit(1)
  858. if args.max_upload_size:
  859. sizeRe = re.match("^(\d+(?:[,.]\d+)?)(?:([bkmgtpe])(?:(?<!b)b?)?)?$", args.max_upload_size.lower())
  860. if not sizeRe:
  861. print("Error: Your max upload size param is broken. Try something like 3M or 2.5Gb.")
  862. sys.exit(1)
  863. uploadSize, modifier = sizeRe.groups()
  864. uploadSize = float(uploadSize.replace(",", "."))
  865. sizes = ["b", "k", "m", "g", "t", "p", "e"]
  866. maxUploadSize = int(uploadSize * pow(1024, sizes.index(modifier or "k")))
  867. if maxUploadSize < 0:
  868. print("Error: Your max upload size can't be negative")
  869. sys.exit(1)
  870. if args.ssl and not HAVE_SSL:
  871. print("Error: SSL is not available, please install pyssl (python-openssl).")
  872. sys.exit(1)
  873. if args.cert and not args.key:
  874. print("Error: Please specify a key along with your cert.")
  875. sys.exit(1)
  876. if not args.ssl and (args.cert or args.key):
  877. print("Error: You need to enable ssl with --ssl when specifying certs/keys.")
  878. sys.exit(1)
  879. if args.auth:
  880. dpos = args.auth.find(":")
  881. if dpos <= 0 or dpos == (len(args.auth)-1):
  882. print("Error: User and password for HTTP basic authentication need to be both at least one character and have to be separated by a \":\".")
  883. sys.exit(1)
  884. if args.realm and not args.auth:
  885. print("You can only specify a realm when HTTP basic authentication is enabled.")
  886. sys.exit(1)
  887. if args.compression != "none" and not args.tar:
  888. print("Error: Please use --tar if you want to tar everything.")
  889. sys.exit(1)
  890. if args.tar and args.upload:
  891. print("Error: --tar mode will not work with uploads.")
  892. sys.exit(1)
  893. if args.tar and args.list_dir:
  894. print("Error: --tar mode will not work with directory listings.")
  895. sys.exit(1)
  896. compression = None
  897. if args.compression:
  898. if args.compression in TarFileHandler.compressionMethods:
  899. compression = args.compression
  900. else:
  901. print("Error: Compression mode '%s' is unknown." % args.compression)
  902. sys.exit(1)
  903. if args.ipv4_only and args.ipv6_only:
  904. print("You can't listen both on IPv4 and IPv6 \"only\".")
  905. sys.exit(1)
  906. if args.ipv6_only and not socket.has_ipv6:
  907. print("Your system does not support IPv6.")
  908. sys.exit(1)
  909. mode = None
  910. if args.upload:
  911. mode = ServeFile.MODE_UPLOAD
  912. elif args.list_dir:
  913. mode = ServeFile.MODE_LISTDIR
  914. elif args.tar:
  915. mode = ServeFile.MODE_SINGLETAR
  916. else:
  917. mode = ServeFile.MODE_SINGLE
  918. server = None
  919. try:
  920. server = ServeFile(args.target, args.port, mode, args.ssl)
  921. if maxUploadSize > 0:
  922. server.setMaxUploadSize(maxUploadSize)
  923. if args.ssl and args.key:
  924. cert = args.cert or args.key
  925. server.setSSLKeys(cert, args.key)
  926. if args.auth:
  927. user, password = args.auth.split(":", 1)
  928. server.setAuth(user, password, args.realm)
  929. if compression and compression != "none":
  930. server.setCompression(compression)
  931. if args.ipv4_only or not socket.has_ipv6:
  932. server.setIPv6(False)
  933. if args.ipv6_only:
  934. server.setIPv4(False)
  935. server.serve()
  936. except ServeFileException as e:
  937. print(e)
  938. sys.exit(1)
  939. print("Good bye.")
  940. if __name__ == '__main__':
  941. main()