-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.c
79 lines (70 loc) · 1.6 KB
/
io.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>
#include "include/bot.h"
#include "include/irc.h"
#include "include/utils.h"
#include "include/io.h"
void display_message(struct IRC_CTX *ctx) {
// fprintf(stdout, "%s %s", ctx->msg->src->host, ctx->msg->text);
debug_print_msg(ctx->msg);
}
void write_to_socket(struct IRC_CTX *ctx, char *fmt, ...) {
ssize_t ret = 0;
char sbuf[WRITE_BUF_SIZE_BYTES] = {'\0'};
va_list ap;
va_start(ap, fmt);
vsnprintf(sbuf, WRITE_BUF_SIZE_BYTES, fmt, ap);
va_end(ap);
printf("<< %s", sbuf);
ret = write(ctx->sockfd, sbuf, strlen(sbuf));
switch (ret) {
case -1:
error("write");
case 0:
printf("wrote nothing");
default: ;
}
}
int listen_server(struct IRC_CTX *ctx) {
ssize_t ret = 0;
size_t offset = 0;
char read_buf[READ_BUF_SIZE_BYTES];
int return_value = 0;
int checked_valid = 0;
for (;;) {
memset(read_buf + offset, 0, READ_BUF_SIZE_BYTES - offset);
ret = read(ctx->sockfd, read_buf + offset,
(READ_BUF_SIZE_BYTES - 1) - offset);
checked_valid = 0;
switch (ret) {
case -1:
close(ctx->sockfd);
perror("Read error");
goto cleanup;
break;
case 0:
printf("Finished reading.");
goto cleanup;
break;
default:
while (!checked_valid) {
parse_read_buffer(ctx, read_buf, &offset);
if (!ctx->msg->valid)
free_msg(ctx->msg);
else
checked_valid = 1;
}
handle_irc_command(ctx);
display_message(ctx);
break;
}
}
cleanup:
free_context(ctx);
return_value = ret ? errno : ret;
return return_value;
}