Skip to content
Snippets Groups Projects
Commit 00656716 authored by Romain Gabet's avatar Romain Gabet :speech_balloon:
Browse files

partie 6 non clean

parent 46714e11
No related branches found
No related tags found
No related merge requests found
No preview for this file type
File added
No preview for this file type
# Ces variables servent à préciser le compilateur que l'on veut utiliser
# ainsi que les paramètres de compilation
CC=gcc
LD=gcc
CFLAGS=-Wall -W -Werror
LDFLAGS=
# Le nom de l'exécutable à fabriquer
EXE=pawnee
# Les variables HEADERS, CFILES et OBJS vont contenir respectivement
# la listes des fichiers .h, .c et le nom des fichiers .o à fabriquer
# On utilise la directive particulière \$(wildcard ...) qui permet
# de construire automatiquement une liste de fichiers
HEADERS=$(wildcard *.h)
CFILES=$(wildcard *.c)
# Cette construction de variable veut dire : remplacer la chaine ".c" par
# ".o" dans la variable CFILES
# Ceci nous permet de construire la liste des fichiers .o à fabriquer
OBJS=$(CFILES:.c=.o)
# Même utilisation que précédemment. On précise les règles qui
# ne fabrique pas de fichier du nom de leur cible
.PHONY: all clean mrproper
# La règle par défaut déclenche la fabrication de l'exécutable
# par dépendance
all: $(EXE)
# Cette règle permet de construire l'exécutable. Elle dépend des fichiers
# .o et effectue l'édition de lien. Rien de nouveau ici
$(EXE): $(OBJS)
$(LD) $^ $(LDFLAGS) -o $@
# Cette règle permet de construire automatiquement les règles
# de compilation pour chacun des fichiers .c
# l'option -MM de gcc analyse un fichier .c et
# affiche sur sa sortie standard une règle compatible
# make pour le compiler.
# Ceci permet d'ajouter automatiquement les fichiers .h aux dépendances
# des fichiers .o à construire. Ainsi, en modifiant un fichier .h
# tous les fichiers .c qui incluent ce fichier sont recompilés
# Après votre première compilation, regardez le contenu du fichier
# makefile.dep généré afin de comprendre exactement de quoi il retourne.
CFLAGS=-Wall -Wextra -Werror -g
LIB=libhttp_parse.a
makefile.dep: $(CFILES) $(HEADERS)
$(CC) -MM $(CFILES) > $@
SRC=$(wildcard *.c)
OBJS=$(SRC:.c=.o)
HDR=$(wildcard *.h)
# Cette règle efface le fichier de dépendances et les fichiers .o
$(LIB): $(OBJS)
ar rs $@ $^
ranlib $@
clean:
$(RM) $(OBJS) makefile.dep
# Cette règle effectue la précédente et efface en plus l'exécutable
makefile.dep: $(SRC) $(HDR)
$(CC) $(CFLAGS) -MM $(SRC) > $@
.PHONY: clean mrproper
clean:
$(RM) $(OBJS)
mrproper: clean
$(RM) $(EXE)
# On inclue le fichier de dépendance qui va contenir les règles
# de construction des fichiers .o
# S'il n'existe pas, make invoque automatiquement la règle
# qui l'a pour cible
$(RM) $(LIB)
include makefile.dep
include makefile.dep
\ No newline at end of file
......@@ -6,19 +6,61 @@
#include <sys/wait.h>
#include <stdlib.h>
#include "client.h"
#include "http_parse.h"
char* fgets_or_exit(char * buffer, int size, FILE *fd){
char * ret = fgets(buffer,size,fd);
if(ret){
return ret;
} else {
exit(1);
}
}
int is_crlf(const char *str){
return (str[0] == '\r' && str[1] == '\n') || str[0] =='\n';
}
void skip_headers(FILE *client){
//passer les headers files
char buffer[8000];
while(1){
fgets_or_exit(buffer, sizeof(buffer), client);
if (is_crlf(buffer))
break;
}
}
void send_status(FILE *client, int code, const char *reason_phrase){
//transmet le status au client (1ère ligne)
fprintf(client, "HTTP/1.1 %d %s\r\n",code,reason_phrase);
}
void send_response(FILE *client, int code, const char *reason_phrase, const char *message_body){
send_status(client,code,reason_phrase);
//transmet la réponse complète (la suite)
fprintf(client,"Content-Length : 17 \r\n%d %s",code,message_body);
}
/*
char* testCorrect(char* str, int first){
char* strRet;
http_request request;
char *correctStr = "GET / HTTP/1.1";
char *correctStr2 = "GET /inexistant HTTP/1.1";
char *incorrectStrBR = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length:17\r\n\r\n400 Bad request";
char *correctStrOk = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 17\r\n\r\n200 OK";
char *incorrectStrNF = "HTTP/1.1 404 not found\r\nConnection close\r\nContent-Length:17\r\n\r\n404 Not Found";
if(strstr(str,correctStr) == NULL && first == 0) {
strRet=incorrectStrBR;
}else if(!strcmp(str,"\r\n")) {
//start-line à véfifier avec le parse_http_request
if(parse_http_request(str,&request) == -1 && first == 0) {
//strRet=incorrectStrBR;
skip_headers(str);
}else if(!strcmp(correctStr,str)) {
strRet = correctStrOk;
}else if(strcmp(str,correctStr2)){
strRet = incorrectStrNF;
......@@ -28,9 +70,9 @@ char* testCorrect(char* str, int first){
printf("---\n%s\n---",strRet);
return strRet;
}
*/
char* fgets_or_exit(char * buffer, int size, FILE *fd){
/*-------------------
int first = 0;
while(!feof(fd) && fgets(buffer,size,fd) != NULL){
char* resTest = testCorrect(buffer,first);
......@@ -40,11 +82,13 @@ char* fgets_or_exit(char * buffer, int size, FILE *fd){
}
first=0;
exit(1);
}
}*/
int traitementClient(int socket_client){
/* On peut maintenant dialoguer avec le client */
char *motd="Bienvenue client";
char str[8000];
http_request request;
FILE *fd;
fd = fdopen(socket_client, "a+");
fprintf(fd,"Bienvenue client\n");
......@@ -53,6 +97,19 @@ int traitementClient(int socket_client){
exit(1);
}
fgets_or_exit(str,8000,fd);
int parse_ret = parse_http_request(str,&request);
skip_headers(fd);
if (parse_ret == -1) {
if (request.method == HTTP_UNSUPPORTED){
send_response(fd, 405, "Method Not Allowed", "Method Not Allowed\r\n");
}else{
send_response(fd, 400, "Bad Request", "Bad request\r\n");
}
}else if (strcmp(request.target, "/") == 0){
send_response(fd, 200, "OK", motd);
}else{
send_response(fd, 404, "Not Found", "Not Found\r\n");
}
fclose(fd);
return 0;
}
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include "socket.h"
#include <netinet/in.h>
#include <sys/wait.h>
#include <stdlib.h>
#include "client.h"
char* testCorrect(char* str, int first){
// char* size = "";
// sprintf(size, "%ld", strlen(str));
char* strRet;
char *correctStr = "GET / HTTP/1.1";
char *correctStr2 = "GET /inexistant HTTP/1.1";
//double strcat fait bugger
char *incorrectStrBR = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length:17\r\n\r\n400 Bad request";
char *correctStrOk = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 17\r\n\r\n200 OK";
char *incorrectStrNF = "HTTP/1.1 404 not found\r\nConnection close\r\nContent-Length:17\r\n\r\n404 Not Found";
if(strstr(str,correctStr) == NULL && first == 0) {
strRet=incorrectStrBR;
//printf("---\n%s\n---",str);
}else if(!strcmp(str,"\r\n")) {
strRet = correctStrOk;
}else if(strcmp(str,correctStr2)){
strRet = incorrectStrNF;
}else{
strRet = NULL;
}
printf("---\n%s\n---",strRet);
return strRet;
}
char* fgets_or_exit(char * buffer, int size, FILE *fd){
int first = 0;
while(!feof(fd) && fgets(buffer,size,fd) != NULL){
char* resTest = testCorrect(buffer,first);
if(resTest!=NULL)fprintf(fd,"<Notre Serveur> %s\n",resTest);
first=1;
fflush(fd);
}
first=0;
exit(1);
}
int traitementClient(int socket_client){
/* On peut maintenant dialoguer avec le client */
//const char *message_bienvenue = "Bonjour, bienvenue sur mon serveur\nExcogitatum est super his, ut homines quidam ignoti, vilitate ipsa parum cavendi ad colligendos rumores per Antiochiae latera cuncta destinarentur relaturi quae audirent. hi peragranter et dissimulanter honoratorum circulis adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.Sed fruatur sane hoc solacio atque hanc insignem ignominiam, quoniam uni praeter se inusta sit, putet esse leviorem, dum modo, cuius exemplo se consolatur, eius exitum expectet, praesertim cum in Albucio nec Pisonis libidines nec audacia Gabini fuerit ac tamen hac una plaga conciderit, ignominia senatus.Post emensos insuperabilis expeditionis eventus languentibus partium animis, quas periculorum varietas fregerat et laborum, nondum tubarum cessante clangore vel milite locato per stationes hibernas, fortunae saevientis procellae tempestates alias rebus infudere communibus per multa illa et dira facinora Caesaris Galli, qui ex squalore imo miseriarum in aetatis adultae primitiis ad principale culmen insperato saltu provectus ultra terminos potestatis delatae procurrens asperitate nimia cuncta foedabat. propinquitate enim regiae stirpis gentilitateque etiam tum Constantini nominis efferebatur in fastus, si plus v
char str[8000];
FILE *fd;
//status = write(socket_client, message_bienvenue, strlen(message_bienvenue));
fd = fdopen(socket_client, "a+");
fprintf(fd,"Bienvenue client\n");
if(fd == NULL) {
perror("Error opening file");
exit(1);
}
fgets_or_exit(str,8000,fd);
fclose(fd);
return 0;
}
No preview for this file type
// Copyright © 2019, Université de Lille.
// Created: 22 janvier 2019
//
// Corresponding author: Michael Hauspie <michael.hauspie@univ-lille.fr>
// For full author list, see AUTHORS.md file
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/ or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include <string.h>
#include <stdio.h>
#include "http_parse.h"
#define min(a,b) ((a) < (b) ? (a) : (b))
#define in_range(a,b,c) ((a) < (b) ? 0 : ((a) > (c) ? 0 : 1))
int parse_http_request(const char *request_line , http_request *request)
{
if (strncmp(request_line, "GET ", 4) != 0)
{
request->method = HTTP_UNSUPPORTED;
return -1;
}
request->method = HTTP_GET;
/* Find the target start */
const char *target = strchr(request_line, ' ');
if (target == NULL)
return -1;
target++;
/* Find target end and copy target to request */
char *target_end = strchr(target, ' ');
if (target_end == NULL)
return -1;
int size = min(target_end - target, MAX_TARGET_SIZE);
strncpy(request->target, target, size);
/* If target is more than size, \0 is not add to dst, so... */
request->target[size] = '\0';
/* Now http version (only support HTTP/M.m version format) */
/* Quote from RFC:
Additionally, version numbers have been restricted to
single digits, due to the fact that implementations are known to
handle multi-digit version numbers incorrectly.
*/
char *version = target_end + 1;
if (strncmp(version, "HTTP/", 5) != 0)
return -1;
if (!in_range(version[5], '0', '9')) // major
return -1;
if (version[6] != '.') // mandatory dot
return -1;
if (!in_range(version[7], '0', '9')) // minor
return -1;
if (version[8] != '\0' && version[8] != '\r' && version[8] != '\n') // only support version number with 1 digit for major and 1 digit for minor
return -1;
request->http_major = version[5] - '0';
request->http_minor = version[7] - '0';
return 0;
}
#ifdef COMPILE_MAIN
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "usage: %s http_request_line\n", argv[0]);
return 1;
}
http_request r;
if (parse_http_request(argv[1], &r) == -1)
{
fprintf(stderr, "Fails to parse request\n");
if (r.method == HTTP_UNSUPPORTED)
fprintf(stderr, "Unsupported method\n");
return 1;
}
printf("request line: %s\n", argv[1]);
printf("method: %s\n", r.method == HTTP_GET ? "GET" : "UNSUPPORTED");
printf("target: %s\n", r.target);
printf("version: %d.%d\n", r.http_major, r.http_minor);
return 0;
}
#endif
// Copyright © 2019, Université de Lille.
// Created: 22 janvier 2019
//
// Corresponding author: Michael Hauspie <michael.hauspie@univ-lille.fr>
// For full author list, see AUTHORS.md file
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/ or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#ifndef __HTTP_PARSE__
#define __HTTP_PARSE__
// Method supported by the parser
enum http_method {
HTTP_GET,
HTTP_UNSUPPORTED,
};
// The maximum size of the target string.
#define MAX_TARGET_SIZE 1024
// describes a http request
typedef struct
{
enum http_method method;
int http_major;
int http_minor;
char target[MAX_TARGET_SIZE];
} http_request;
/** Parses a http request line.
@param in request_line the line to parse (as a null terminated string). The line can end with '\r\n', '\n' or nothing after the HTTP version
@param out request a valid pointer to a http_request that will be filled by the function
@return -1 if error and 0 on success. If the error is an
unsupported http method, then the method field of request will be set to HTTP_UNSUPPORTED
*/
int parse_http_request(const char *request_line , http_request *request);
#endif
File added
File added
socket.o: socket.c socket.h client.h
client.o: client.c socket.h client.h
client.o: client.c socket.h client.h http_parse.h
http_parse.o: http_parse.c http_parse.h
main.o: main.c socket.h
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment