server.py (gère les cgi-bin avec comme protocole GET grâce à « QUERY_STRING » et ceux
avec le protocole POST via l’entrée standard) :
#!/usr/bin/env python
# coding: utf-8
import socket, sys, os, subprocess
#--------CREE LA SOCKET ET GERE LES PROBLEMES SI DEJA USE--------
def startSocket():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 8080)) #Respectivement sock.bind((adresse, port))
return sock
def getProtocol(response, sock, cli, dir_path):
filePath = response[4:]
splitResult = filePath.split(' ')
filePath = dir_path + splitResult[0]
#--------REQUETE : VERIFICATION TYPE DE FICHIER--------
isHtml = filePath.split('.')
isCgiBin = filePath.split('?')
#--------CGI : PRESENCE DU FICHIER--------
if os.path.exists(isCgiBin[0]) and "cgi-bin" in filePath:
os.environ["QUERY_STRING"] = isCgiBin[1]
popen = subprocess.Popen([isCgiBin[0]], stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read() #Récupération de la sortie standard
cli.send(bytes("HTTP/1.0 200 OK\r\nContent-Type:
text/html;\r\ncharset=utf-8\r\nContent-Language: fr\r\nConnection: keep-
alive\r\n\r\n".encode('UTF-8') + output))
#--------HTML : PRESENCE DU FICHIER--------
elif isHtml[1] == "html" and os.path.exists(filePath):
fichier = open(filePath, "r")
cli.send(bytes("HTTP/1.0 200 OK\r\nContent-Type:
text/html;\r\ncharset=utf-8\r\nContent-Language: fr\r\nConnection: keep-
alive\r\n\r\n".encode('UTF-8') + fichier.read()))
fichier.close()
else:
cli.send(b"HTTP/1.0 404 FILE NOT FOUND")
def postProtocol(response, sock, cli, dir_path):
filePath = response[5:]
splitResult = filePath.split(' ')
filePath = dir_path + splitResult[0]
isCgiBin = filePath.split('?')