Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 5,969 | Comments: 44,489

filter by tags archive

A web server in 30 lines of code


Just found myself writing that, and it was amusing.

import System.Net
import System.IO

if argv.Length != 2:
	print "You must pass [prefix] [path] as parameters"
	return

prefix = argv[0]
path = argv[1]

if not Directory.Exists(path):
	print "Could not find ${path}"
	return

listener = HttpListener()
listener.Prefixes.Add(prefix)
listener.Start()

while true:
	context = listener.GetContext()
	file = Path.GetFileName(context.Request.RawUrl)
	fullPath = Path.Combine(path, file)
	if File.Exists(fullPath):
		context.Response.AddHeader("Content-Disposition","attachment; filename=${file}")
		bytes = File.ReadAllBytes(fullPath)
		context.Response.OutputStream.Write(bytes, 0, bytes.Length)
		context.Response.OutputStream.Flush()
		context.Response.Close()
	else:
		context.Response.StatusCode = 404
		context.Response.Close()

Comments

Tuna Toksoz

the altdotnet style :)

Thomas Krause

But, what happens if you pass something like:

http://localhost/prefix/../../../Windows/System32/Secret.File

Sorry, couldn't resist ;-)

Ayende Rahien

Well, did you note

Path.GetFileName(context.Request.RawUrl)

??

That will stop those attacks

Thomas Krause

Oh, you're right. I missed that somehow. I read something like:

fullPath = Path.Combine(path, context.Request.RawUrl)

Nevermind...

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

  1. Production postmortem: The evil licensing code - 2 hours from now

There are posts all the way to Jul 29, 2015

RECENT SERIES

  1. Production postmortem (5):
    23 Jul 2015 - The case of the native memory leak
  2. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
  3. API Design (7):
    20 Jul 2015 - We’ll let the users sort it out
  4. What is new in RavenDB 3.5 (3):
    15 Jul 2015 - Exploring data in the dark
  5. The RavenDB Comic Strip (3):
    28 May 2015 - Part III – High availability & sleeping soundly
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats