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