1 |
/** |
2 |
* gen_listenerdemo.C: Listener code demo. |
3 |
* |
4 |
* Copyright © 2007 Pippijn van Steenhoven / The Ermyth Team |
5 |
* Rights to this code are as documented in COPYING. |
6 |
* |
7 |
* |
8 |
* Portions of this file were derived from sources bearing the following license: |
9 |
* Copyright © 2005 William Pitcock <nenolod -at- nenolod.net> |
10 |
* Rights to this code are as documented in doc/pod/license.pod. |
11 |
* |
12 |
* $Id: gen_listenerdemo.C,v 1.4 2007-08-30 19:56:22 pippijn Exp $ |
13 |
*/ |
14 |
|
15 |
#include "atheme.h" |
16 |
#include <ermyth/module.h> |
17 |
#include "datastream.h" |
18 |
#include "connection.h" |
19 |
|
20 |
static char const rcsid[] = "$Id: gen_listenerdemo.C,v 1.4 2007-08-30 19:56:22 pippijn Exp $"; |
21 |
|
22 |
REGISTER_MODULE ("contrib/gen_listenerdemo", false, "William Pitcock <nenolod -at- nenolod.net>"); |
23 |
|
24 |
static connection_t *listener; |
25 |
|
26 |
static int |
27 |
my_read (connection_t *cptr, char *buf) |
28 |
{ |
29 |
int n; |
30 |
|
31 |
if ((n = read (cptr->fd, buf, BUFSIZE)) > 0) |
32 |
{ |
33 |
buf[n] = '\0'; |
34 |
cnt.bin += n; |
35 |
} |
36 |
|
37 |
return n; |
38 |
} |
39 |
|
40 |
static void |
41 |
do_packet (char *buf) |
42 |
{ |
43 |
char *ptr, buf2[BUFSIZE * 2]; |
44 |
static char tmp[BUFSIZE * 2 + 1]; |
45 |
|
46 |
while ((ptr = strchr (buf, '\n'))) |
47 |
{ |
48 |
*ptr = '\0'; |
49 |
|
50 |
if (ptr != buf && *(ptr - 1) == '\r') |
51 |
*(ptr - 1) = '\0'; |
52 |
|
53 |
snprintf (buf2, (BUFSIZE * 2), "%s%s", tmp, buf); |
54 |
*tmp = '\0'; |
55 |
|
56 |
slog (LG_DEBUG, "-{incoming}-> %s", buf2); |
57 |
|
58 |
buf = ptr + 1; |
59 |
} |
60 |
|
61 |
if (*buf) |
62 |
{ |
63 |
strlcpy (tmp, buf, BUFSIZE * 2); |
64 |
tmp[BUFSIZE * 2] = '\0'; |
65 |
} |
66 |
} |
67 |
|
68 |
static void |
69 |
my_rhandler (connection_t *cptr) |
70 |
{ |
71 |
char buf[BUFSIZE * 2]; |
72 |
|
73 |
if (!my_read (cptr, buf)) |
74 |
cptr->close (); |
75 |
|
76 |
do_packet (buf); |
77 |
} |
78 |
|
79 |
static void |
80 |
do_listen (connection_t *cptr) |
81 |
{ |
82 |
connection_t::accept_tcp (cptr, my_rhandler, sendq_flush); |
83 |
slog (LG_DEBUG, "do_listen(): accepted %d", cptr->fd); |
84 |
} |
85 |
|
86 |
bool |
87 |
_modinit (module *m) |
88 |
{ |
89 |
listener = connection_t::open_listener_tcp ("127.0.0.1", 7100, do_listen); |
90 |
|
91 |
return true; |
92 |
} |
93 |
|
94 |
void |
95 |
_moddeinit (void) |
96 |
{ |
97 |
listener->close (); |
98 |
} |