-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy-concurrent.c
More file actions
199 lines (164 loc) · 7.01 KB
/
proxy-concurrent.c
File metadata and controls
199 lines (164 loc) · 7.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#include <stdio.h>
#include "csapp.h"
/* Recommended max cache and object sizes */
#define MAX_CACHE_SIZE 1049000 // 최대 캐시 크기
#define MAX_OBJECT_SIZE 102400 // 최대 객체 크기
void doit(int clientfd);
void parse_uri(char *uri, char *hostname, char *port, char *path);
void clienterror(int fd, char *cause, char *errnum, char *shortmsg, char *longmsg);
void read_requesthdrs(rio_t *rp);
void *thread(void *vargp);
/* You won't lose style points for including this long line in your code */
static const char *user_agent_hdr =
"User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.3) Gecko/20120305 "
"Firefox/10.0.3\r\n";
int main(int argc, char **argv) {
int listenfd, *clientfd;
char hostname[MAXLINE], port[MAXLINE];
socklen_t clientlen;
struct sockaddr_storage clientaddr;
pthread_t tid; // 새로운 스레드 ID를 저장하기 위한 변수
if (argc != 2)
{
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}
// SIGPIPE : 소켓을 통해 데이터를 쓰려고 할 때, 읽는 쪽이 이미 닫혀 있거나 연결이 끊어진 상태에 쓰기 작업을 시도할 때 발생
// signal(SIGPIPE, SIG_IGN) - SIGPIPE 신호를 무시하도록 설정 (클라이언트 연결이 끊어지더라도 프로세스가 종료되지 않도록 방지)
// concurrent 환경에서 다른 스레드가 소켓을 닫더라도 현재 작업중인 스레드가 종료되지 않고 계속 실행되도록 하기 위함!!
signal(SIGPIPE, SIG_IGN);
listenfd = Open_listenfd(argv[1]);
while(1)
{
clientlen = sizeof(clientaddr);
clientfd = Malloc(sizeof(int));
*clientfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
Getnameinfo((SA *)&clientaddr, clientlen, hostname, MAXLINE, port, MAXLINE, 0);
printf("Accepted connection from (%s %s)\n", hostname, port);
Pthread_create(&tid, NULL, thread, clientfd); // 새로운 스레드를 생성하여 클라이언트와 통신을 담당하는 함수 thread 실행
}
}
void *thread(void *vargp)
{
int clientfd = *((int *)vargp);
Pthread_detach(pthread_self());
Free(vargp);
doit(clientfd);
Close(clientfd);
return NULL;
}
/*
* < 함수 전체 로직 >
* 1. 클라이언트의 요청을 받아들인다.
* 2. 받은 요청을 파싱하여 요청된 URI를 추출한다.
* 3. 추출된 URI를 기반으로 서버에 새로운 연결을 생성한다.
* 4. 클라이언트로 받은 요청을 서버로 전송한다.
* 5. 서버로부터의 응답을 읽어들인다.
* 6. 받은 응답을 클라이언트에게 전송한다.
*/
void doit(int clientfd)
{
int serverfd; // 서버 소켓 파일 디스크립터
char request_buf[MAXLINE], response_buf[MAX_OBJECT_SIZE]; // 요청, 응답 데이터용 버퍼
char method[MAXLINE], uri[MAXLINE], path[MAXLINE];
char hostname[MAXLINE], port[MAXLINE];
rio_t request_rio, response_rio;
// 1. 클라이언트의 요청을 받아들인다.
Rio_readinitb(&request_rio, clientfd); // 클라이언트 소켓과 request 버퍼 연결
Rio_readlineb(&request_rio, request_buf, MAXLINE); // request 버퍼에서 한 줄 읽어들임
printf("Request header: %s\n", request_buf);
sscanf(request_buf, "%s %s", method, uri); // 버퍼의 내용을 method와 uri에 저장
// 2. 받은 요청을 파싱하여 요청된 URI를 추출한다.
parse_uri(uri, hostname, port, path); // uri 분석하는 함수
sprintf(request_buf, "%s /%s %s\r\n", method, path, "HTTP/1.0");
sprintf(request_buf, "%sConnection: close\r\n", request_buf);
sprintf(request_buf, "%sProxy-Connection: close\r\n", request_buf);
sprintf(request_buf, "%s%s\r\n", request_buf, user_agent_hdr);
if (strcasecmp(method, "GET") && strcasecmp(method, "HEAD"))
{
clienterror(clientfd, method, "501", "Not Implemented", "Proxy does not implement this method");
return;
}
// 3. 추출된 URI를 기반으로 서버에 새로운 연결을 생성한다.
serverfd = Open_clientfd(hostname, port); // 서버 소켓 열기
if (serverfd < 0)
{
clienterror(clientfd, hostname, "404", "Not found", "Proxy couldn't connect to the server");
return;
}
printf("%s\n", request_buf);
// 4. 클라이언트로 받은 요청을 서버로 전송한다.
Rio_writen(serverfd, request_buf, strlen(request_buf)); // 요청 내용 서버에 보내기
Rio_readinitb(&response_rio, serverfd); // 서버 소켓과 response 버퍼 연결
// 5. 서버로부터의 응답을 읽어들인다.
// 응답 버퍼에서 한줄 씩 읽어와서 클라이언트 소켓에 전송
ssize_t n;
while ((n = Rio_readlineb(&response_rio, response_buf, MAX_OBJECT_SIZE)) > 0)
{
// 6. 받은 응답을 클라이언트에게 전송한다.
Rio_writen(clientfd, response_buf, n);
if(!strcmp(response_buf, "\r\n")) // 응답 헤더 전송
break;
}
while ((n = Rio_readlineb(&response_rio, response_buf, MAX_OBJECT_SIZE)) > 0)
{
Rio_writen(clientfd, response_buf, n); // 응답 본문 전송
}
Close(serverfd); // 서버 소켓 닫기
}
/*
* parse_uri -> 파싱해야 할 데이터
* URI: http://www.cmu.edu:8080/hub/index.html
* Hostname: www.cmu.edu
* Port: 8080
* Path: hub/index.html
*/
void parse_uri(char *uri, char *hostname, char *port, char *path)
{
printf("====> uri: %s\n", uri);
char *hostname_ptr = strstr(uri, "//") != NULL ? strstr(uri, "//") + 2 : uri + 1;
char *port_ptr = strstr(hostname_ptr, ":");
char *path_ptr = strstr(hostname_ptr, "/");
if (path_ptr > 0)
{
*path_ptr = '\0';
strcpy(path, path_ptr + 1);
}
if (port_ptr > 0)
{
*port_ptr = '\0';
strcpy(port, port_ptr + 1);
}
strcpy(hostname, hostname_ptr);
printf("====> host: %s, port: %s, path: %s\n\n", hostname, port, path);
}
// 웹 서버에서 오류가 발생했을 때 클라이언트에게 오류를 알리는 함수
void clienterror(int fd, char *cause, char *errnum, char *shortmsg, char *longmsg)
{
char buf[MAXLINE], body[MAXBUF];
// sprintf() - 형식화된 문자열을 생성하여 주어진 버퍼에 저장
sprintf(body, "<html><title>Proxy Error</title>");
sprintf(body, "%s<body bgcolor=""ffffff"">\r\n", body);
sprintf(body, "%s%s: %s\r\n", body, errnum, shortmsg);
sprintf(body, "%s<p>%s: %s\r\n", body, longmsg, cause);
sprintf(body, "%s<hr><em>The Proxy server<\em>\r\n", body);
sprintf(buf, "HTTP/1.0 %s %s\r\n", errnum, shortmsg);
Rio_writen(fd, buf, strlen(buf));
sprintf(buf, "Content-type: text/html\r\n");
Rio_writen(fd, buf, strlen(buf));
sprintf(buf, "Content-length: %d\r\n\r\n", (int)strlen(body));
Rio_writen(fd, buf, strlen(buf));
Rio_writen(fd, body, strlen(body)); // 위의 body 내용 출력
}
// 클라이언트로부터 수신된 HTTP 요청 헤더를 읽고 출력하는 함수
void read_requesthdrs(rio_t *rp)
{
char buf[MAXLINE];
Rio_readlineb(rp, buf, MAXLINE);
while(strcmp(buf, "\r\n"))
{
Rio_readlineb(rp, buf, MAXLINE);
printf("%s", buf);
}
return;
}