|
1 |
|
2 #include "irc_conn.h" |
|
3 |
|
4 #include <stdlib.h> |
|
5 #include <string.h> |
|
6 |
|
7 void irc_conn_on_line (char *line_buf, void *arg) |
|
8 { |
|
9 struct irc_line line; |
|
10 int err; |
|
11 |
|
12 // log |
|
13 printf("<<< %s\n", line_buf); |
|
14 |
|
15 // parse |
|
16 if ((err = irc_line_parse(&line, line_buf))) |
|
17 printf("!!! Invalid line: %s: %s\n", line_buf, error_name(err)); |
|
18 |
|
19 else |
|
20 printf("\tprefix=%s, command=%s, args={%s, %s, %s, ...}\n", |
|
21 line.prefix, line.command, line.args[0], line.args[1], line.args[2] |
|
22 ); |
|
23 } |
|
24 |
|
25 err_t irc_conn_create (struct irc_conn **conn_ptr, struct sock_stream *sock, const struct irc_conn_config *config, struct error_info *err) |
|
26 { |
|
27 struct irc_conn *conn; |
|
28 |
|
29 // alloc new state struct |
|
30 if ((conn = calloc(1, sizeof(struct irc_conn))) == NULL) |
|
31 return SET_ERROR(err, ERR_CALLOC); |
|
32 |
|
33 // create the line_proto, with our on_line handler |
|
34 if (line_proto_create(&conn->lp, sock, IRC_LINE_MAX * 1.5, &irc_conn_on_line, conn, err)) |
|
35 return ERROR_CODE(err); |
|
36 |
|
37 // send the initial messages |
|
38 if ( |
|
39 irc_conn_NICK(conn, config->nickname) |
|
40 || irc_conn_USER(conn, config->username, config->realname) |
|
41 ) |
|
42 return ERROR_CODE(err); |
|
43 |
|
44 // ok |
|
45 *conn_ptr = conn; |
|
46 |
|
47 return SUCCESS; |
|
48 } |
|
49 |
|
50 err_t irc_conn_send (struct irc_conn *conn, const struct irc_line *line) |
|
51 { |
|
52 char line_buf[IRC_LINE_MAX + 2]; |
|
53 err_t err; |
|
54 |
|
55 // format |
|
56 if ((err = irc_line_build(line, line_buf))) |
|
57 return err; |
|
58 |
|
59 // log |
|
60 printf(">>> %s\n", line_buf); |
|
61 |
|
62 // add CRLF |
|
63 strcat(line_buf, "\r\n"); |
|
64 |
|
65 // send using line_proto |
|
66 return line_proto_write(conn->lp, line_buf); |
|
67 } |
|
68 |
|
69 err_t irc_conn_NICK (struct irc_conn *conn, const char *nickname) |
|
70 { |
|
71 // NICK <nickname> |
|
72 struct irc_line line = { |
|
73 NULL, "NICK", { nickname, NULL } |
|
74 }; |
|
75 |
|
76 // send it |
|
77 return irc_conn_send(conn, &line); |
|
78 } |
|
79 |
|
80 err_t irc_conn_USER (struct irc_conn *conn, const char *username, const char *realname) |
|
81 { |
|
82 // USER <user> <mode> <unused> <realname> |
|
83 struct irc_line line = { |
|
84 NULL, "USER", { username, "0", "*", realname } |
|
85 }; |
|
86 |
|
87 // send it |
|
88 return irc_conn_send(conn, &line); |
|
89 } |
|
90 |