]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
Create StreamSocket for IO hooking implementation
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <zlib.h>
16 #include "transport.h"
17 #include <iostream>
18
19 /* $ModDesc: Provides zlib link support for servers */
20 /* $LinkerFlags: -lz */
21 /* $ModDep: transport.h */
22
23 /*
24  * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
25  * a flush after each chunk. A frame may contain multiple lines
26  * and should be treated as raw binary data.
27  */
28
29 /* Status of a connection */
30 enum izip_status { IZIP_CLOSED = 0, IZIP_OPEN };
31
32 /** Represents an zipped connections extra data
33  */
34 class izip_session : public classbase
35 {
36  public:
37         z_stream c_stream;      /* compression stream */
38         z_stream d_stream;      /* uncompress stream */
39         izip_status status;     /* Connection status */
40         std::string outbuf;     /* Holds output buffer (compressed) */
41         std::string inbuf;      /* Holds input buffer (compressed) */
42 };
43
44 class ModuleZLib : public Module
45 {
46         izip_session* sessions;
47
48         /* Used for stats z extensions */
49         float total_out_compressed;
50         float total_in_compressed;
51         float total_out_uncompressed;
52         float total_in_uncompressed;
53
54         /* Used for reading data from the wire and compressing data to. */
55         char *net_buffer;
56         unsigned int net_buffer_size;
57  public:
58
59         ModuleZLib(InspIRCd* Me)
60                 : Module(Me)
61         {
62                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
63
64                 sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
65                 for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
66                         sessions[i].status = IZIP_CLOSED;
67
68                 total_out_compressed = total_in_compressed = 0;
69                 total_out_uncompressed = total_in_uncompressed = 0;
70                 Implementation eventlist[] = { I_OnStats, I_OnRequest };
71                 ServerInstance->Modules->Attach(eventlist, this, 2);
72
73                 // Allocate a buffer which is used for reading and writing data
74                 net_buffer_size = ServerInstance->Config->NetBufferSize;
75                 net_buffer = new char[net_buffer_size];
76         }
77
78         ~ModuleZLib()
79         {
80                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
81                 delete[] sessions;
82                 delete[] net_buffer;
83         }
84
85         Version GetVersion()
86         {
87                 return Version("$Id$", VF_VENDOR, API_VERSION);
88         }
89
90
91         /* Handle BufferedSocketHook API requests */
92         const char* OnRequest(Request* request)
93         {
94                 ISHRequest* ISR = (ISHRequest*)request;
95                 if (strcmp("IS_NAME", request->GetId()) == 0)
96                 {
97                         /* Return name */
98                         return "zip";
99                 }
100                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
101                 {
102                         ISR->Sock->AddIOHook(this);
103                         return "OK";
104                 }
105                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
106                 {
107                         ISR->Sock->DelIOHook();
108                         return "OK";
109                 }
110                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
111                 {
112                         /* Check for completion of handshake
113                          * (actually, this module doesnt handshake)
114                          */
115                         return "OK";
116                 }
117                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
118                 {
119                         /* Attach certificate data to the inspsocket
120                          * (this module doesnt do that, either)
121                          */
122                         return NULL;
123                 }
124                 return NULL;
125         }
126
127         /* Handle stats z (misc stats) */
128         ModResult OnStats(char symbol, User* user, string_list &results)
129         {
130                 if (symbol == 'z')
131                 {
132                         std::string sn = ServerInstance->Config->ServerName;
133
134                         /* Yeah yeah, i know, floats are ew.
135                          * We used them here because we'd be casting to float anyway to do this maths,
136                          * and also only floating point numbers can deal with the pretty large numbers
137                          * involved in the total throughput of a server over a large period of time.
138                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
139                          * can still hold more.
140                          */
141                         float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
142                         float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
143
144                         float total_compressed = total_in_compressed + total_out_compressed;
145                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
146
147                         float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
148
149                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
150
151                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
152                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
153                         sprintf(combined_ratio, "%3.2f%%", total_r);
154
155                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
156                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
157                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
158                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
159                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_original_outbound_traffic        = "+outbound_ratio);
160                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_orignal_inbound_traffic         = "+inbound_ratio);
161                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS total_size_of_original_traffic        = "+combined_ratio);
162                         return MOD_RES_PASSTHRU;
163                 }
164
165                 return MOD_RES_PASSTHRU;
166         }
167
168         void OnStreamSocketConnect(StreamSocket* user)
169         {
170                 OnStreamSocketAccept(user, 0, 0);
171         }
172
173         void OnRawSocketAccept(StreamSocket* user, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*)
174         {
175                 int fd = user->GetFd();
176
177                 izip_session* session = &sessions[fd];
178
179                 /* Just in case... */
180                 session->outbuf.clear();
181
182                 session->c_stream.zalloc = (alloc_func)0;
183                 session->c_stream.zfree = (free_func)0;
184                 session->c_stream.opaque = (voidpf)0;
185
186                 session->d_stream.zalloc = (alloc_func)0;
187                 session->d_stream.zfree = (free_func)0;
188                 session->d_stream.opaque = (voidpf)0;
189
190                 /* If we cant call this, well, we're boned. */
191                 if (inflateInit(&session->d_stream) != Z_OK)
192                 {
193                         session->status = IZIP_CLOSED;
194                         return;
195                 }
196
197                 /* Same here */
198                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
199                 {
200                         inflateEnd(&session->d_stream);
201                         session->status = IZIP_CLOSED;
202                         return;
203                 }
204
205                 /* Just in case, do this last */
206                 session->status = IZIP_OPEN;
207         }
208
209         void OnStreamSocketClose(StreamSocket* user)
210         {
211                 int fd = user->GetFd();
212                 CloseSession(&sessions[fd]);
213         }
214
215         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
216         {
217                 int fd = user->GetFd();
218                 /* Find the sockets session */
219                 izip_session* session = &sessions[fd];
220
221                 if (session->status == IZIP_CLOSED)
222                         return -1;
223
224                 if (session->inbuf.empty())
225                 {
226                         /* Read read_buffer_size bytes at a time to the buffer (usually 2.5k) */
227                         int readresult = read(fd, net_buffer, net_buffer_size);
228
229                         if (readresult < 0)
230                         {
231                                 if (errno == EINTR || errno == EAGAIN)
232                                         return 0;
233                         }
234                         if (readresult <= 0)
235                                 return -1;
236
237                         total_in_compressed += readresult;
238
239                         /* Copy the compressed data into our input buffer */
240                         session->inbuf.append(net_buffer, readresult);
241                 }
242
243                 size_t in_len = session->inbuf.length();
244                 char* buffer = ServerInstance->GetReadBuffer();
245                 int count = ServerInstance->Config->NetBufferSize;
246
247                 /* Prepare decompression */
248                 session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
249                 session->d_stream.avail_in = in_len;
250
251                 session->d_stream.next_out = (Bytef*)buffer;
252                 /* Last byte is reserved for NULL terminating that beast */
253                 session->d_stream.avail_out = count - 1;
254
255                 /* Z_SYNC_FLUSH: Do as much as possible */
256                 int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
257                 /* TODO CloseStream() in here at random places */
258                 switch (ret)
259                 {
260                         case Z_NEED_DICT:
261                         case Z_STREAM_ERROR:
262                                 /* This is one of the 'not supposed to happen' things.
263                                  * Memory corruption, anyone?
264                                  */
265                                 Error(session, "General Error. This is not supposed to happen :/");
266                                 break;
267                         case Z_DATA_ERROR:
268                                 Error(session, "Decompression failed, malformed data");
269                                 break;
270                         case Z_MEM_ERROR:
271                                 Error(session, "Out of memory");
272                                 break;
273                         case Z_BUF_ERROR:
274                                 /* This one is non-fatal, buffer is just full
275                                  * (can't happen here).
276                                  */
277                                 Error(session, "Internal error. This is not supposed to happen.");
278                                 break;
279                         case Z_STREAM_END:
280                                 /* This module *never* generates these :/ */
281                                 Error(session, "End-of-stream marker received");
282                                 break;
283                         case Z_OK:
284                                 break;
285                         default:
286                                 /* NO WAI! This can't happen. All errors are handled above. */
287                                 Error(session, "Unknown error");
288                                 break;
289                 }
290                 if (ret != Z_OK)
291                 {
292                         return -1;
293                 }
294
295                 /* Update the inbut buffer */
296                 unsigned int input_compressed = in_len - session->d_stream.avail_in;
297                 session->inbuf = session->inbuf.substr(input_compressed);
298
299                 /* Update counters (Old size - new size) */
300                 unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
301                 total_in_uncompressed += uncompressed_length;
302
303                 /* Null-terminate the buffer -- this doesnt harm binary data */
304                 recvq.append(buffer, uncompressed_length);
305                 return 1;
306         }
307
308         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
309         {
310                 int fd = user->GetFd();
311                 izip_session* session = &sessions[fd];
312
313                 if(session->status != IZIP_OPEN)
314                         /* Seriously, wtf? */
315                         return -1;
316
317                 int ret;
318
319                 /* This loop is really only supposed to run once, but in case 'compr'
320                  * is filled up somehow we are prepared to handle this situation.
321                  */
322                 unsigned int offset = 0;
323                 do
324                 {
325                         /* Prepare compression */
326                         session->c_stream.next_in = (Bytef*)sendq.data() + offset;
327                         session->c_stream.avail_in = sendq.length() - offset;
328
329                         session->c_stream.next_out = (Bytef*)net_buffer;
330                         session->c_stream.avail_out = net_buffer_size;
331
332                         /* Compress the text */
333                         ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
334                         /* TODO CloseStream() in here at random places */
335                         switch (ret)
336                         {
337                                 case Z_OK:
338                                         break;
339                                 case Z_BUF_ERROR:
340                                         /* This one is non-fatal, buffer is just full
341                                          * (can't happen here).
342                                          */
343                                         Error(session, "Internal error. This is not supposed to happen.");
344                                         break;
345                                 case Z_STREAM_ERROR:
346                                         /* This is one of the 'not supposed to happen' things.
347                                          * Memory corruption, anyone?
348                                          */
349                                         Error(session, "General Error. This is also not supposed to happen.");
350                                         break;
351                                 default:
352                                         Error(session, "Unknown error");
353                                         break;
354                         }
355
356                         if (ret != Z_OK)
357                                 return 0;
358
359                         /* Space before - space after stuff was added to this */
360                         unsigned int compressed = net_buffer_size - session->c_stream.avail_out;
361                         unsigned int uncompressed = sendq.length() - session->c_stream.avail_in;
362
363                         /* Make it skip the data which was compressed already */
364                         offset += uncompressed;
365
366                         /* Update stats */
367                         total_out_uncompressed += uncompressed;
368                         total_out_compressed += compressed;
369
370                         /* Add compressed to the output buffer */
371                         session->outbuf.append((const char*)net_buffer, compressed);
372                 } while (session->c_stream.avail_in != 0);
373
374                 /* Lets see how much we can send out */
375                 ret = write(fd, session->outbuf.data(), session->outbuf.length());
376
377                 /* Check for errors, and advance the buffer if any was sent */
378                 if (ret > 0)
379                         session->outbuf = session->outbuf.substr(ret);
380                 else if (ret < 1)
381                 {
382                         if (errno == EAGAIN)
383                                 return 0;
384                         else
385                         {
386                                 session->outbuf.clear();
387                                 return -1;
388                         }
389                 }
390
391                 return 1;
392         }
393
394         void Error(izip_session* session, const std::string &text)
395         {
396                 ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
397         }
398
399         void CloseSession(izip_session* session)
400         {
401                 if (session->status == IZIP_OPEN)
402                 {
403                         session->status = IZIP_CLOSED;
404                         session->outbuf.clear();
405                         inflateEnd(&session->d_stream);
406                         deflateEnd(&session->c_stream);
407                 }
408         }
409
410 };
411
412 MODULE_INIT(ModuleZLib)
413