afd8cde5102827516e0795b2b67e803c105ad378
[cascardo/rnetproxy.git] / proto_detect.c
1 #include <gnet.h>
2 #include <glib.h>
3 #include "proto_detect.h"
4 #include "jabber.h"
5
6 static void proto_connect (net_hook_t* hook)
7 {
8 }
9
10 static void proto_close (net_hook_t* hook)
11 {
12 }
13
14 static void proto_write (net_hook_t* hook)
15 {
16 }
17
18 static void proto_read (net_hook_t* hook, gchar* buffer, size_t len)
19 {
20   net_hook_t* new_hook;
21   GString* str;
22   str = (GString*) hook->data;
23   g_string_append_len (str, buffer, len);
24   if (str->len >= 7)
25     {
26       if (!strncmp (str->str, "<stream", 7))
27         {
28           /* Connection is a Jabber client */
29           g_debug ("Connection from %s is a Jabber client.",
30                    hook->conn->hostname);
31           new_hook = jabber_hook_new (hook->conn);
32           new_hook->read (new_hook, str->str, str->len);
33           proto_detect_destroy (hook);
34         }
35       else
36         {
37           g_debug ("Unrecognized protocol from %s.",
38                    hook->conn->hostname);
39           gnet_conn_disconnect (hook->conn);
40           gnet_conn_unref (hook->conn);
41           proto_detect_destroy (hook);
42         }
43     }
44 }
45
46 net_hook_t* proto_detect_new (GConn* conn)
47 {
48   net_hook_t* hook;
49   hook = g_slice_new (net_hook_t);
50   hook->conn = conn;
51   hook->peer = NULL;
52   hook->server = FALSE;
53   hook->connect = proto_connect;
54   hook->close = proto_close;
55   hook->write = proto_write;
56   hook->read = proto_read;
57   hook->data = g_string_sized_new (128);
58   gnet_conn_set_callback (hook->conn, nethook_event, hook);
59   return hook;
60 }
61
62 void proto_detect_destroy (net_hook_t* hook)
63 {
64   if (hook->data != NULL)
65     {
66       g_string_free (hook->data, TRUE);
67     }
68   g_slice_free (net_hook_t, hook);
69 }