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