1👍
it seems like you use a single file /home/user/file.c
for every request. so, race condition is imminent.
there are two solutions :
1) write to a temporary file. temporary file can be generated from tempfile module, or you can just create random filename.
2) write to a memory file. you can use StringIO
(or faster cStringIO
) module to create such file, and then you can pipe it to gcc.
for solution 1), there are many ways to do this but here’s my solution:
change this part
data=request.GET.get('content','')
handle=open('/home/user/file.c','r+')
handle.write(request.GET['content'])
handle.close()
to
# you need 'random', 'string', 'os' modules imported
data=request.GET.get('content','')
filename = "".join(random.sample(string.letters, 10)) + ".c" #sample 10 letters from A-z
filepath = os.path.join('home','user','filename')
handle=open(filepath,'r+')
handle.write(request.GET['content'])
handle.close()
res = commands.getstatusoutput('gcc -Wall %s -o /home/user/file;home/user/file' %filepath)
os.remove(filepath) #remove temporary file after compiling
also, the commands
module is deprecated. you should use subprocess.call
.
0👍
You should generate random file with each request and use that. The tempfile module can help you with that.
Also if you don’t care about produced binary, using -o /dev/null
is good idea.
- [Answer]-Why is 'username' declared twice in the stock UserCreationForm?
- [Answer]-Django Queryset Iteration Optimization
Source:stackexchange.com