src/irc_conn.c
changeset 18 dedf137b504f
child 19 8c80580ccde9
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/irc_conn.c	Sat Feb 28 22:47:39 2009 +0200
@@ -0,0 +1,90 @@
+
+#include "irc_conn.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+void irc_conn_on_line (char *line_buf, void *arg) 
+{
+    struct irc_line line;
+    int err;
+    
+    // log
+    printf("<<< %s\n", line_buf);
+
+    // parse
+    if ((err = irc_line_parse(&line, line_buf)))
+        printf("!!! Invalid line: %s: %s\n", line_buf, error_name(err));
+
+    else
+        printf("\tprefix=%s, command=%s, args={%s, %s, %s, ...}\n",
+                line.prefix, line.command, line.args[0], line.args[1], line.args[2]
+        );
+}
+
+err_t irc_conn_create (struct irc_conn **conn_ptr, struct sock_stream *sock, const struct irc_conn_config *config, struct error_info *err)
+{
+    struct irc_conn *conn;
+
+    // alloc new state struct
+    if ((conn = calloc(1, sizeof(struct irc_conn))) == NULL)
+        return SET_ERROR(err, ERR_CALLOC);
+
+    // create the line_proto, with our on_line handler
+    if (line_proto_create(&conn->lp, sock, IRC_LINE_MAX * 1.5, &irc_conn_on_line, conn, err))
+        return ERROR_CODE(err);
+
+    // send the initial messages
+    if (
+            irc_conn_NICK(conn, config->nickname)
+        ||  irc_conn_USER(conn, config->username, config->realname)
+    )
+        return ERROR_CODE(err);
+
+    // ok
+    *conn_ptr = conn;
+
+    return SUCCESS;
+}
+
+err_t irc_conn_send (struct irc_conn *conn, const struct irc_line *line)
+{
+    char line_buf[IRC_LINE_MAX + 2];
+    err_t err;
+
+    // format
+    if ((err = irc_line_build(line, line_buf)))
+        return err;
+    
+    // log
+    printf(">>> %s\n", line_buf);
+
+    // add CRLF
+    strcat(line_buf, "\r\n");
+
+    // send using line_proto
+    return line_proto_write(conn->lp, line_buf);
+}
+
+err_t irc_conn_NICK (struct irc_conn *conn, const char *nickname)
+{
+    // NICK <nickname>
+    struct irc_line line = {
+        NULL, "NICK", { nickname, NULL }
+    };
+    
+    // send it
+    return irc_conn_send(conn, &line);
+}
+
+err_t irc_conn_USER (struct irc_conn *conn, const char *username, const char *realname)
+{
+    // USER <user> <mode> <unused> <realname>
+    struct irc_line line = {
+        NULL, "USER", { username, "0", "*", realname }
+    };
+    
+    // send it
+    return irc_conn_send(conn, &line);
+}
+