Connection events are handled by hooks
[cascardo/rnetproxy.git] / improxy.c
1 #include <glib.h>
2 #include <gnet.h>
3 #include <stdio.h>
4 #include "log.h"
5 #include "nethook.h"
6 #include "proto_detect.h"
7
8 #define CONFFILE SYSCONFDIR "/improxy.conf"
9
10 void client_event (GConn* conn, GConnEvent* event, gpointer data)
11 {
12   net_hook_t* hook;
13   hook = (net_hook_t*) data;
14   switch (event->type)
15     {
16     case GNET_CONN_CONNECT:
17       hook->connect (hook);
18       break;
19     case GNET_CONN_READ:
20       hook->read (hook, event->buffer, event->length);
21       break;
22     case GNET_CONN_WRITE:
23       hook->write (hook);
24       break;
25     case GNET_CONN_CLOSE:
26       hook->close (hook);
27       break;
28     default:
29       g_warning ("Received an unexpected client event.");
30       break;
31     }
32 }
33
34 void new_client (GServer* server, GConn* conn, gpointer data)
35 {
36   net_hook_t* hook;
37   if (conn == NULL)
38     {
39       g_critical ("Server has received an error event.");
40       return;
41     }
42   g_message ("Received connection from %s.", conn->hostname);
43   hook = proto_detect_new (conn);
44   gnet_conn_set_callback (conn, client_event, hook);
45   gnet_conn_read (conn);
46 }
47
48 static gchar* configfile;
49
50 static GOptionEntry opt_entries[] =
51   {
52     { "config-file", 'c', 0, G_OPTION_ARG_FILENAME, &configfile,
53       "Configuration file location", "file" },
54     { NULL }
55   };
56
57 int main (int argc, char** argv)
58 {
59
60   GOptionContext* opt_ctx;
61   GKeyFile *keyfile;
62   GInetAddr* inetaddr;
63   gchar* conf_address;
64   gint port;
65
66   gnet_init ();
67   im_log_init ();
68
69   configfile = CONFFILE;
70   opt_ctx = g_option_context_new ("");
71   g_option_context_add_main_entries (opt_ctx, opt_entries, NULL);
72   if (!g_option_context_parse (opt_ctx, &argc, &argv, NULL))
73     {
74       g_log (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL,
75              "Could not parse command line options.");
76     }
77   g_option_context_free (opt_ctx);
78   
79   keyfile =  g_key_file_new ();
80
81   g_key_file_load_from_file (keyfile, configfile, G_KEY_FILE_NONE, NULL);
82
83   conf_address = g_key_file_get_string (keyfile, "global", "address", NULL);
84   port = g_key_file_get_integer (keyfile, "global", "port", NULL);
85
86   g_message ("Listen address is %s:%d.", conf_address, port);
87
88   inetaddr = gnet_inetaddr_new_nonblock (conf_address, port);
89   gnet_server_new (inetaddr, port, new_client, NULL);
90
91   g_main_loop_run (g_main_loop_new (g_main_context_default (), TRUE));
92
93   return 0;
94
95 }