CS:APP proxy lab 笔记

这个 lab 我没有认真写,参考了潜龙勿用的实现方法,然后在上面优化了一下

但是博客实现有点问题,改进了一下,然后完整的代码如下:

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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#include <stdio.h>
#include "csapp.h"

/* Recommended max cache and object sizes */
#define MAX_CACHE_SIZE 1049000
#define MAX_OBJECT_SIZE 102400

/* 线程池与有限缓冲区配置 */
#define NTHREADS 4
#define SBUFSIZE 16

/* 缓存槽位数量上限(1MB 总空间下,20个槽位足以容纳大小混合对象) */
#define CACHE_OBJS_COUNT 20

/* sbuf 有限缓冲区定义 */
typedef struct {
int *buf;
int n;
int front;
int rear;
sem_t mutex;
sem_t slots;
sem_t items;
} sbuf_t;

void sbuf_init(sbuf_t *sp, int n);
void sbuf_deinit(sbuf_t *sp);
void sbuf_insert(sbuf_t *sp, int item);
int sbuf_remove(sbuf_t *sp);

/* 缓存结构与读者-写者控制 */
typedef struct {
char uri[MAXLINE]; /* 缓存键:完整请求 URI */
char object[MAX_OBJECT_SIZE]; /* 缓存的原始 HTTP 响应字节流(含响应头与响应体) */
size_t size; /* 实际存储的字节数 */
int valid; /* 1 表示有效占用,0 表示空闲槽位 */
unsigned long lru_time; /* 逻辑时间戳,值越大表示越最近使用 */
} cache_block_t;

typedef struct {
cache_block_t blocks[CACHE_OBJS_COUNT];
size_t total_size; /* 当前缓存池已占用的总字节数 */
unsigned long global_time; /* 全局单调递增逻辑时钟 */
int readcnt; /* 当前正在读缓存的线程数 */
sem_t mutex; /* 保护 readcnt 和 global_time */
sem_t w; /* 写者互斥锁 */
} cache_t;

void cache_init(void);
int cache_find_and_send(const char *uri, int connfd);
void cache_insert(const char *uri, const char *buf, size_t size);

struct Uri {
char host[MAXLINE];
char port[MAXLINE];
char path[MAXLINE];
};

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";

sbuf_t sbuf;
cache_t cache;

void *thread(void *vargp);
void doit(int connfd);
void parse_uri(char *uri, struct Uri *uri_data);
void build_header(char *http_header, size_t max_len, struct Uri *uri_data, rio_t *client_rio);

int main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t clientlen;
struct sockaddr_storage clientaddr;
pthread_t tid;

if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}

Signal(SIGPIPE, SIG_IGN);

listenfd = Open_listenfd(argv[1]);

/* 初始化连接队列、内存缓存池与工作线程池 */
sbuf_init(&sbuf, SBUFSIZE);
cache_init();
for (int i = 0; i < NTHREADS; i++) {
Pthread_create(&tid, NULL, thread, NULL);
}

while (1) {
clientlen = sizeof(clientaddr);
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
sbuf_insert(&sbuf, connfd);
}

sbuf_deinit(&sbuf);
return 0;
}

void *thread(void *vargp)
{
Pthread_detach(pthread_self());
while (1) {
int connfd = sbuf_remove(&sbuf);
doit(connfd);
Close(connfd);
}
return NULL;
}

void doit(int connfd)
{
char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE];
char uri_copy[MAXLINE];
char server[MAXLINE * 2];
rio_t rio, server_rio;

Rio_readinitb(&rio, connfd);
if (Rio_readlineb(&rio, buf, MAXLINE) <= 0) {
return;
}
sscanf(buf, "%s %s %s", method, uri, version);

if (strcasecmp(method, "GET")) {
printf("Proxy does not implement the method: %s\n", method);
return;
}

/* 备份原始完整 URI 作为缓存 Key(因为后续 parse_uri 会原地截断 uri) */
strncpy(uri_copy, uri, sizeof(uri_copy) - 1);
uri_copy[sizeof(uri_copy) - 1] = '\0';

/* 1. 优先查询内存缓存,命中则直接发回客户端并返回 */
if (cache_find_and_send(uri_copy, connfd)) {
return;
}

/* 2. 缓存未命中,正常解析并向源服务器发起请求 */
struct Uri *uri_data = (struct Uri *)Malloc(sizeof(struct Uri));
parse_uri(uri, uri_data);
build_header(server, sizeof(server), uri_data, &rio);

int serverfd = Open_clientfd(uri_data->host, uri_data->port);
if (serverfd < 0) {
printf("connection failed\n");
Free(uri_data);
return;
}

Rio_readinitb(&server_rio, serverfd);
Rio_writen(serverfd, server, strlen(server));

/* 3. 接收源服务器响应,边转发给客户端边累积到临时缓存缓冲区 */
char cache_buf[MAX_OBJECT_SIZE];
size_t total_bytes = 0;
ssize_t n;

while ((n = Rio_readnb(&server_rio, buf, MAXLINE)) > 0) {
Rio_writen(connfd, buf, n);
if (total_bytes + n <= MAX_OBJECT_SIZE) {
memcpy(cache_buf + total_bytes, buf, n);
}
total_bytes += n;
}

/* 4. 若对象大小未超过 MAX_OBJECT_SIZE,写入全局缓存池 */
if (total_bytes > 0 && total_bytes <= MAX_OBJECT_SIZE) {
cache_insert(uri_copy, cache_buf, total_bytes);
}

Close(serverfd);
Free(uri_data);
}

void parse_uri(char *uri, struct Uri *uri_data)
{
uri_data->host[0] = '\0';
strcpy(uri_data->port, "80");
strcpy(uri_data->path, "/");

char *hostpose = strstr(uri, "//");
if (hostpose == NULL) {
char *pathpose = strstr(uri, "/");
if (pathpose != NULL) {
strcpy(uri_data->path, pathpose);
}
return;
} else {
char *portpose = strstr(hostpose + 2, ":");
if (portpose != NULL) {
int tmp;
sscanf(portpose + 1, "%d%s", &tmp, uri_data->path);
snprintf(uri_data->port, sizeof(uri_data->port), "%d", tmp);
*portpose = '\0';
} else {
char *pathpose = strstr(hostpose + 2, "/");
if (pathpose != NULL) {
strcpy(uri_data->path, pathpose);
*pathpose = '\0';
}
}
strcpy(uri_data->host, hostpose + 2);
}
}

void build_header(char *http_header, size_t max_len, struct Uri *uri_data, rio_t *client_rio)
{
char buf[MAXLINE], request_hdr[MAXLINE], other_hdr[MAXLINE], host_hdr[MAXLINE];

snprintf(request_hdr, sizeof(request_hdr), "GET %s HTTP/1.0\r\n", uri_data->path);
other_hdr[0] = '\0';
host_hdr[0] = '\0';

while (Rio_readlineb(client_rio, buf, MAXLINE) > 0) {
if (strcmp(buf, "\r\n") == 0) {
break;
}
if (!strncasecmp(buf, "Host:", 5)) {
strncpy(host_hdr, buf, sizeof(host_hdr) - 1);
host_hdr[sizeof(host_hdr) - 1] = '\0';
continue;
}
if (!strncasecmp(buf, "User-Agent:", 11) ||
!strncasecmp(buf, "Connection:", 11) ||
!strncasecmp(buf, "Proxy-Connection:", 17)) {
continue;
}
if (strlen(other_hdr) + strlen(buf) < sizeof(other_hdr) - 1) {
strcat(other_hdr, buf);
}
}

if (strlen(host_hdr) == 0) {
snprintf(host_hdr, sizeof(host_hdr), "Host: %s\r\n", uri_data->host);
}

snprintf(http_header, max_len, "%s%s%s%s%s%s\r\n",
request_hdr,
host_hdr,
"Connection: close\r\n",
"Proxy-Connection: close\r\n",
user_agent_hdr,
other_hdr);
}

/* sbuf 有限缓冲区实现 */
void sbuf_init(sbuf_t *sp, int n)
{
sp->buf = Calloc(n, sizeof(int));
sp->n = n;
sp->front = sp->rear = 0;
Sem_init(&sp->mutex, 0, 1);
Sem_init(&sp->slots, 0, n);
Sem_init(&sp->items, 0, 0);
}

void sbuf_deinit(sbuf_t *sp)
{
Free(sp->buf);
}

void sbuf_insert(sbuf_t *sp, int item)
{
P(&sp->slots);
P(&sp->mutex);
sp->buf[(++sp->rear) % (sp->n)] = item;
V(&sp->mutex);
V(&sp->items);
}

int sbuf_remove(sbuf_t *sp)
{
int item;
P(&sp->items);
P(&sp->mutex);
item = sp->buf[(++sp->front) % (sp->n)];
V(&sp->mutex);
V(&sp->slots);
return item;
}

/* 缓存模块实现(读者优先 + LRU) */
void cache_init(void)
{
cache.total_size = 0;
cache.global_time = 0;
cache.readcnt = 0;
Sem_init(&cache.mutex, 0, 1);
Sem_init(&cache.w, 0, 1);
for (int i = 0; i < CACHE_OBJS_COUNT; i++) {
cache.blocks[i].valid = 0;
cache.blocks[i].size = 0;
cache.blocks[i].lru_time = 0;
}
}

/* 读者函数:查找命中后先拷贝到本地缓冲区再解锁发送,避免长时间持锁 */
int cache_find_and_send(const char *uri, int connfd)
{
int hit = 0;
char local_buf[MAX_OBJECT_SIZE];
size_t local_size = 0;

/* 进入读者临界区 */
P(&cache.mutex);
cache.readcnt++;
if (cache.readcnt == 1) {
P(&cache.w); /* 第一个读者锁住写者 */
}
V(&cache.mutex);

for (int i = 0; i < CACHE_OBJS_COUNT; i++) {
if (cache.blocks[i].valid && strcmp(cache.blocks[i].uri, uri) == 0) {
hit = 1;
local_size = cache.blocks[i].size;
memcpy(local_buf, cache.blocks[i].object, local_size);

/* 更新 LRU 时间戳(用 mutex 保护全局时钟与时间戳写入,防止多读者竞争) */
P(&cache.mutex);
cache.blocks[i].lru_time = ++cache.global_time;
V(&cache.mutex);
break;
}
}

/* 离开读者临界区 */
P(&cache.mutex);
cache.readcnt--;
if (cache.readcnt == 0) {
V(&cache.w); /* 最后一个读者释放写锁 */
}
V(&cache.mutex);

/* 在锁外执行网络写入,不阻塞其他并发线程 */
if (hit) {
Rio_writen(connfd, local_buf, local_size);
}
return hit;
}

/* 写者函数:LRU 淘汰并插入新缓存对象 */
void cache_insert(const char *uri, const char *buf, size_t size)
{
P(&cache.w); /* 获取独占写锁 */

/* 1. 若总容量不足,循环淘汰 lru_time 最小的有效槽位 */
while (cache.total_size + size > MAX_CACHE_SIZE) {
int victim = -1;
unsigned long min_time = (unsigned long)-1;
for (int i = 0; i < CACHE_OBJS_COUNT; i++) {
if (cache.blocks[i].valid && cache.blocks[i].lru_time < min_time) {
min_time = cache.blocks[i].lru_time;
victim = i;
}
}
if (victim == -1) {
break;
}
cache.blocks[victim].valid = 0;
cache.total_size -= cache.blocks[victim].size;
}

/* 2. 查找空闲槽位;若所有槽位均被占满(例如存了20个小文件),同样按 LRU 淘汰一个 */
int target = -1;
for (int i = 0; i < CACHE_OBJS_COUNT; i++) {
if (!cache.blocks[i].valid) {
target = i;
break;
}
}
if (target == -1) {
unsigned long min_time = (unsigned long)-1;
for (int i = 0; i < CACHE_OBJS_COUNT; i++) {
if (cache.blocks[i].lru_time < min_time) {
min_time = cache.blocks[i].lru_time;
target = i;
}
}
cache.total_size -= cache.blocks[target].size;
}

/* 3. 写入缓存数据 */
strncpy(cache.blocks[target].uri, uri, MAXLINE - 1);
cache.blocks[target].uri[MAXLINE - 1] = '\0';
memcpy(cache.blocks[target].object, buf, size);
cache.blocks[target].size = size;
cache.blocks[target].valid = 1;
cache.blocks[target].lru_time = ++cache.global_time;
cache.total_size += size;

V(&cache.w); /* 释放写锁 */
}