Detects Jabber protocol and hook to it
[cascardo/rnetproxy.git] / proto_detect.c
index 8fd790e..afd8cde 100644 (file)
@@ -1,6 +1,7 @@
 #include <gnet.h>
 #include <glib.h>
 #include "proto_detect.h"
+#include "jabber.h"
 
 static void proto_connect (net_hook_t* hook)
 {
@@ -16,6 +17,30 @@ static void proto_write (net_hook_t* hook)
 
 static void proto_read (net_hook_t* hook, gchar* buffer, size_t len)
 {
+  net_hook_t* new_hook;
+  GString* str;
+  str = (GString*) hook->data;
+  g_string_append_len (str, buffer, len);
+  if (str->len >= 7)
+    {
+      if (!strncmp (str->str, "<stream", 7))
+       {
+         /* Connection is a Jabber client */
+         g_debug ("Connection from %s is a Jabber client.",
+                  hook->conn->hostname);
+         new_hook = jabber_hook_new (hook->conn);
+         new_hook->read (new_hook, str->str, str->len);
+         proto_detect_destroy (hook);
+       }
+      else
+       {
+         g_debug ("Unrecognized protocol from %s.",
+                  hook->conn->hostname);
+         gnet_conn_disconnect (hook->conn);
+         gnet_conn_unref (hook->conn);
+         proto_detect_destroy (hook);
+       }
+    }
 }
 
 net_hook_t* proto_detect_new (GConn* conn)
@@ -29,11 +54,16 @@ net_hook_t* proto_detect_new (GConn* conn)
   hook->close = proto_close;
   hook->write = proto_write;
   hook->read = proto_read;
-  hook->data = NULL;
+  hook->data = g_string_sized_new (128);
+  gnet_conn_set_callback (hook->conn, nethook_event, hook);
   return hook;
 }
 
 void proto_detect_destroy (net_hook_t* hook)
 {
+  if (hook->data != NULL)
+    {
+      g_string_free (hook->data, TRUE);
+    }
   g_slice_free (net_hook_t, hook);
 }