Read line by line from client and write it to server.
[cascardo/rnetproxy.git] / pop.c
1 /*
2 ** Copyright (C) 2006 Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
3 ** Copyright (C) 2009 Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
4 **  
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **  
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ** GNU General Public License for more details.
14 **  
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 **  
19 */
20
21 #include <gnet.h>
22 #include <glib.h>
23 #include <string.h>
24 #include "nethook.h"
25 #include "pop.h"
26
27 typedef struct
28 {
29   net_read orig_read;
30   gpointer orig_data;
31   GString *buffer;
32   GString *line;
33 } pop_t;
34
35 static int
36 pop_getline (pop_t *pop)
37 {
38   char * end;
39   size_t len;
40   if (pop->buffer->len == 0)
41     return -1;
42   end = memchr (pop->buffer->str, '\n', pop->buffer->len);
43   if (end == NULL)
44     return -1;
45   len = end - pop->buffer->str + 1;
46   g_string_truncate (pop->line, 0);
47   g_string_append_len (pop->line, pop->buffer->str, len);
48   g_string_erase (pop->buffer, 0, len);
49   return 0;
50 }
51
52 static void
53 pop_read (net_hook_t *hook, gchar *buffer, size_t len)
54 {
55   pop_t *pop = hook->data;
56   g_string_append_len (pop->buffer, buffer, len);
57   hook->data = pop->orig_data;
58   while (pop_getline (pop) == 0)
59     pop->orig_read (hook, pop->line->str, pop->line->len);
60   hook->data = pop;
61 }
62
63 net_hook_t *
64 pop_hook_new (net_hook_t *layer)
65 {
66   pop_t *pop;
67   pop = g_slice_new (pop_t);
68   pop->orig_read = layer->read;
69   pop->orig_data = layer->data;
70   pop->buffer = g_string_sized_new (4096);
71   pop->line = g_string_sized_new (4096);
72   layer->read = pop_read;
73   layer->data = pop;
74   return layer;
75 }
76
77 void
78 pop_destroy (net_hook_t *hook)
79 {
80   pop_t *pop = hook->data;
81   g_string_free (pop->buffer, TRUE);
82   g_string_free (pop->line, TRUE);
83   hook->read = pop->orig_read;
84   hook->data = pop->orig_data;
85   g_slice_free (net_hook_t, (gpointer) pop);
86 }