Reputation: 347
I have created a simple http server for my family on the local network, when i add a html file and png picture and tried to view the HTML file, my image cannot load.
It says:
"The image “http://...:255/header.png” cannot be displayed because it contains errors."
Here is a bit of my code
elif self.path.endswith(".bm"): #our dynamic content
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
f= open(curdir + sep + self.path)
ren = self.render(f.read())
self.wfile.write(ren)
return
elif self.path.endswith('.png'):
print "IMAGE WANTED!"
self.send_response(200)
self.send_header('Content-type', 'image/png')
self.end_headers()
f = open(curdir + sep + self.path)
self.wfile.write(f.read())
return
elif self.path.endswith('.jpg'):
print "IMAGE WANTED!"
self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
f= open(curdir + sep + self.path)
print f.read()
self.wfile.write(f.read())
return
elif self.path.endswith(".esp"):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This Format Is Not Supported Any More, Upgrade To BM Script")
return
They all work except for the png and jpeg section. BM script I made myself, same with esp so that is just nothing
Upvotes: 2
Views: 3660
Reputation: 287755
The default mode of open
is 'r'
, which stands for reading text data and does automatic EOL conversion on Windows. Replace f = open(curdir + sep + self.path); self.wfile.write(f.read())
with
fn = os.path.normpath(os.path.join(curdir, self.path))
if not fn.startswith(abspath + os.path.sep):
raise Exception('Path traversal attempt')
with open(fn, 'rb') as f:
self.wfile.write(f.read())
The with
statement fixes the leak of file handles. Alternatively (on Python < 2.5), you can call f.close()
manually.
os.path.join
(for which you may need to import os.path
at the beginning of the file) is a cleaner filename construction mechanism than string concatenation. The check that the resulting filename is in the directory you expect prevents the path traversal vulnerability that would allow anyone to read all the files on your system.
Upvotes: 7