Browse Source

Fix imports and unicode handling for Python3

Sebastian Lohff 1 year ago
parent
commit
0e33743293
1 changed files with 21 additions and 19 deletions
  1. 21
    19
      servefile

+ 21
- 19
servefile View File

@@ -14,7 +14,6 @@ import base64
14 14
 import cgi
15 15
 import datetime
16 16
 import mimetypes
17
-import urllib
18 17
 import os
19 18
 import re
20 19
 import select
@@ -27,10 +26,12 @@ import time
27 26
 try:
28 27
     import BaseHTTPServer
29 28
     import SocketServer
29
+    from urllib import quote, unquote
30 30
 except ImportError:
31 31
     # both have different names in python3
32 32
     import http.server as BaseHTTPServer
33 33
     import socketserver as SocketServer
34
+    from urllib.parse import quote, unquote
34 35
 
35 36
 # only activate SSL if available
36 37
 HAVE_SSL = False
@@ -56,7 +57,7 @@ class FileBaseHandler(BaseHTTPServer.BaseHTTPRequestHandler):
56 57
 		Returns True if a redirect was issued. """
57 58
 		if not fileName:
58 59
 			fileName = self.fileName
59
-		if urllib.unquote(self.path) != "/" + fileName:
60
+		if unquote(self.path) != "/" + fileName:
60 61
 			self.send_response(302)
61 62
 			self.send_header('Location', '/' + fileName)
62 63
 			self.end_headers()
@@ -346,12 +347,12 @@ class DirListingHandler(FileBaseHandler):
346 347
 				<p>The requestet URL %s was not found on this server</p>
347 348
 				<p><a href="/">Back to /</a>
348 349
 				</body>
349
-				</html>""" % self.escapeHTML(urllib.unquote(self.path))
350
+				</html>""" % self.escapeHTML(unquote(self.path))
350 351
 			self.send_header("Content-Length", str(len(errorMsg)))
351 352
 			self.send_header('Connection', 'close')
352 353
 			self.end_headers()
353 354
 			if not head:
354
-				self.wfile.write(errorMsg)
355
+				self.wfile.write(errorMsg.encode())
355 356
 
356 357
 	def escapeHTML(self, htmlstr):
357 358
 		entities = [("<", "&lt;"), (">", "&gt;")]
@@ -378,7 +379,7 @@ class DirListingHandler(FileBaseHandler):
378 379
 				<td class="size">%s</td>
379 380
 				<td class="type">%s</td>
380 381
 			</tr>
381
-		""" % (urllib.quote(item), item, lastModified, fileSize, fileType))
382
+		""" % (quote(item), item, lastModified, fileSize, fileType))
382 383
 
383 384
 	def sendDirectoryListing(self, path, head):
384 385
 		""" Generate a directorylisting for path and send it """
@@ -414,7 +415,7 @@ class DirListingHandler(FileBaseHandler):
414 415
 			</tr>
415 416
 		</thead>
416 417
 		<tbody>
417
-		""" % {'path': os.path.normpath(urllib.unquote(self.path))}
418
+		""" % {'path': os.path.normpath(unquote(self.path))}
418 419
 		footer = """</tbody></table></div>
419 420
 <div class="footer"><a href="http://seba-geek.de/stuff/servefile/">servefile %(version)s</a></div>
420 421
 <script>
@@ -540,7 +541,7 @@ class DirListingHandler(FileBaseHandler):
540 541
 		self.send_header("Content-Length", str(len(listing)))
541 542
 		self.send_header('Connection', 'close')
542 543
 		self.end_headers()
543
-		self.wfile.write(listing)
544
+		self.wfile.write(listing.encode())
544 545
 
545 546
 	def convertSize(self, size):
546 547
 		for ext in "KMGT":
@@ -552,7 +553,7 @@ class DirListingHandler(FileBaseHandler):
552 553
 		return (size, ext.strip())
553 554
 
554 555
 	def getCleanPath(self):
555
-		urlPath = os.path.normpath(urllib.unquote(self.path)).strip("/")
556
+		urlPath = os.path.normpath(unquote(self.path)).strip("/")
556 557
 		path = os.path.join(self.targetDir, urlPath)
557 558
 		return path
558 559
 
@@ -594,7 +595,8 @@ class FilePutter(BaseHTTPServer.BaseHTTPRequestHandler):
594 595
 		length = self.getContentLength()
595 596
 		if length < 0:
596 597
 			return
597
-		ctype = self.headers.getheader('Content-Type')
598
+		print(self.headers)
599
+		ctype = self.headers.get('Content-Type')
598 600
 
599 601
 		# check for multipart/form-data.
600 602
 		if not (ctype and ctype.lower().startswith("multipart/form-data")):
@@ -615,7 +617,7 @@ class FilePutter(BaseHTTPServer.BaseHTTPRequestHandler):
615 617
 			return
616 618
 
617 619
 		# write file down to disk, send a 200 afterwards
618
-		target = open(destFileName, "w")
620
+		target = open(destFileName, "wb")
619 621
 		bytesLeft = length
620 622
 		while bytesLeft > 0:
621 623
 			bytesToRead = min(self.blockSize, bytesLeft)
@@ -638,7 +640,7 @@ class FilePutter(BaseHTTPServer.BaseHTTPRequestHandler):
638 640
 		if length < 0:
639 641
 			return
640 642
 
641
-		fileName = urllib.unquote(self.path)
643
+		fileName = unquote(self.path)
642 644
 		if fileName == "/":
643 645
 			# if no filename was given we have to generate one
644 646
 			fileName = str(time.time())
@@ -685,7 +687,7 @@ class FilePutter(BaseHTTPServer.BaseHTTPRequestHandler):
685 687
 		self.send_header('Content-Length', str(len(msg)))
686 688
 		self.send_header('Connection', 'close')
687 689
 		self.end_headers()
688
-		self.wfile.write(msg)
690
+		self.wfile.write(msg.encode())
689 691
 
690 692
 	def getTargetName(self, fname):
691 693
 		""" Generate a clean and secure filename.
@@ -831,7 +833,7 @@ class ServeFile():
831 833
 				# we couldn't find any ip address
832 834
 				proc = None
833 835
 		if proc:
834
-			ips = proc.stdout.read().strip().split("\n")
836
+			ips = proc.stdout.read().decode().strip().split("\n")
835 837
 
836 838
 			# filter out ips we are not listening on
837 839
 			if not self.listenIPv6:
@@ -877,7 +879,7 @@ class ServeFile():
877 879
 		for ip in self.getIPs() + ["127.0.0.1", "::1"]:
878 880
 			altNames.append("IP:%s" % ip)
879 881
 		altNames.append("DNS:localhost")
880
-		ext = crypto.X509Extension("subjectAltName", False, ",".join(altNames))
882
+		ext = crypto.X509Extension(b"subjectAltName", False, (",".join(altNames)).encode())
881 883
 		req.add_extensions([ext])
882 884
 
883 885
 		req.set_pubkey(pkey)
@@ -901,8 +903,8 @@ class ServeFile():
901 903
 		self.key = pkey
902 904
 
903 905
 		print("done.")
904
-		print("SHA1 fingerprint:", cert.digest("sha1"))
905
-		print("MD5  fingerprint:", cert.digest("md5"))
906
+		print("SHA1 fingerprint:", cert.digest("sha1").decode())
907
+		print("MD5  fingerprint:", cert.digest("md5").decode())
906 908
 
907 909
 	def _getCert(self):
908 910
 		return self.cert
@@ -913,7 +915,7 @@ class ServeFile():
913 915
 	def setAuth(self, user, password, realm=None):
914 916
 		if not user or not password:
915 917
 			raise ServeFileException("User and password both need to be at least one character.")
916
-		self.auth = base64.b64encode("%s:%s" % (user, password))
918
+		self.auth = base64.b64encode(("%s:%s" % (user, password)).encode()).decode()
917 919
 		self.authrealm = realm
918 920
 
919 921
 	def _createServer(self, handler, withv6=False):
@@ -975,7 +977,7 @@ class ServeFile():
975 977
 		else:
976 978
 			pwPart = ""
977 979
 			if self.auth:
978
-				pwPart = base64.b64decode(self.auth) + "@"
980
+				pwPart = base64.b64decode(self.auth).decode() + "@"
979 981
 			for ip in ips:
980 982
 				if ":" in ip:
981 983
 					ip = "[%s]" % ip
@@ -1091,7 +1093,7 @@ class AuthenticationHandler():
1091 1093
 			errorMsg = "<html><head><title>401 - Unauthorized</title></head><body><h1>401 - Unauthorized</h1></body></html>"
1092 1094
 			self.send_header("Content-Length", str(len(errorMsg)))
1093 1095
 			self.end_headers()
1094
-			self.wfile.write(errorMsg)
1096
+			self.wfile.write(errorMsg.encode())
1095 1097
 
1096 1098
 
1097 1099
 def main():

Loading…
Cancel
Save