Skip to content

Commit 81ac500

Browse files
committed
Use getline to prevent incomplete messages being read
1 parent b22248e commit 81ac500

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/server.c

+9-8
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,8 @@ void print_client_addr(struct sockaddr_in addr) {
171171
/* Handle all communication with the client */
172172
void *handle_client(void *arg) {
173173
char buff_out[BUFFER_SZ];
174-
char buff_in[BUFFER_SZ / 2];
174+
char *buff_in;
175+
size_t buff_in_size;
175176
int rlen;
176177

177178
cli_count++;
@@ -181,20 +182,21 @@ void *handle_client(void *arg) {
181182
print_client_addr(cli->addr);
182183
printf(" referenced by %d\n", cli->uid);
183184

185+
FILE *input_stream = fdopen(cli->connfd, "r");
186+
184187
// protocol negotiation
185-
if ((rlen = read(cli->connfd, buff_in, sizeof(buff_in) - 1)) < 0) {
188+
if ((rlen = getline(&buff_in, &buff_in_size, input_stream)) < 0) {
186189
printf("version negotation: error reading from socket\n");
187190
goto CLIENT_CLOSE;
188191
}
189-
buff_in[rlen] = '\0';
190192
strip_newline(buff_in);
191-
char* cmd = strtok(buff_in, " ");
193+
char *cmd = strtok(buff_in, " ");
192194
if (cmd == NULL || cmd[0] != 'v') {
193195
printf("version negotiation: client command not 'v'\n");
194196

195197
goto CLIENT_CLOSE;
196198
}
197-
char* client_version = strtok(NULL, " ");
199+
char *client_version = strtok(NULL, " ");
198200
if (client_version == NULL) {
199201
printf("version negotiation: unable to parse client version\n");
200202
send_message_self("can't parse version\n", cli);
@@ -221,8 +223,7 @@ void *handle_client(void *arg) {
221223
printf("sent serialized canvas\n");
222224

223225
/* Receive input from client */
224-
while ((rlen = read(cli->connfd, buff_in, sizeof(buff_in) - 1)) > 0) {
225-
buff_in[rlen] = '\0';
226+
while ((rlen = getline(&buff_in, &buff_in_size, input_stream)) > 0) {
226227
buff_out[0] = '\0';
227228
strip_newline(buff_in);
228229

@@ -277,7 +278,7 @@ void *handle_client(void *arg) {
277278
}
278279
free(msg);
279280
}
280-
CLIENT_CLOSE:
281+
CLIENT_CLOSE:
281282

282283
/* Close connection */
283284
close(cli->connfd);

0 commit comments

Comments
 (0)