]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
5ee3779bd93b1a7258d665c9eb7ba095b12eeb57
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <string>
18 #include <vector>
19
20 #include "zlib.h"
21
22 #include "inspircd_config.h"
23 #include "configreader.h"
24 #include "users.h"
25 #include "channels.h"
26 #include "modules.h"
27
28 #include "socket.h"
29 #include "hashcomp.h"
30 #include "inspircd.h"
31
32 #include "transport.h"
33
34 /* $ModDesc: Provides zlib link support for servers */
35 /* $LinkerFlags: -lz */
36 /* $ModDep: transport.h */
37
38 /*
39  * Compressed data is transmitted across the link in the following format:
40  *
41  *   0   1   2   3   4 ... n
42  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
43  * |       n       |              Z0 -> Zn                         |
44  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
45  *
46  * Where: n is the size of a frame, in network byte order, 4 bytes.
47  * Z0 through Zn are Zlib compressed data, n bytes in length.
48  *
49  * If the module fails to read the entire frame, then it will buffer
50  * the portion of the last frame it received, then attempt to read
51  * the next part of the frame next time a write notification arrives.
52  *
53  * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
54  * a flush after each frame. A frame may contain multiple lines
55  * and should be treated as raw binary data.
56  *
57  */
58
59 /* Status of a connection */
60 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
61
62 /* Maximum transfer size per read operation */
63 const unsigned int CHUNK = 128 * 1024;
64
65 /* This class manages a compressed chunk of data preceeded by
66  * a length count.
67  *
68  * It can handle having multiple chunks of data in the buffer
69  * at any time.
70  */
71 class CountedBuffer : public classbase
72 {
73         std::string buffer;             /* Current buffer contents */
74         unsigned int amount_expected;   /* Amount of data expected */
75  public:
76         CountedBuffer()
77         {
78                 amount_expected = 0;
79         }
80
81         /** Adds arbitrary compressed data to the buffer.
82          * - Binsry safe, of course.
83          */
84         void AddData(unsigned char* data, int data_length)
85         {
86                 buffer.append((const char*)data, data_length);
87                 this->NextFrameSize();
88         }
89
90         /** Works out the size of the next compressed frame
91          */
92         void NextFrameSize()
93         {
94                 if ((!amount_expected) && (buffer.length() >= 4))
95                 {
96                         /* We have enough to read an int -
97                          * Yes, this is safe, but its ugly. Give me
98                          * a nicer way to read 4 bytes from a binary
99                          * stream, and push them into a 32 bit int,
100                          * and i'll consider replacing this.
101                          */
102                         amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
103                         buffer = buffer.substr(4);
104                 }
105         }
106
107         /** Gets the next frame and returns its size, or returns
108          * zero if there isnt one available yet.
109          * A frame can contain multiple plaintext lines.
110          * - Binary safe.
111          */
112         int GetFrame(unsigned char* frame, int maxsize)
113         {
114                 if (amount_expected)
115                 {
116                         /* We know how much we're expecting...
117                          * Do we have enough yet?
118                          */
119                         if (buffer.length() >= amount_expected)
120                         {
121                                 int j = 0;
122                                 for (unsigned int i = 0; i < amount_expected; i++, j++)
123                                         frame[i] = buffer[i];
124
125                                 buffer = buffer.substr(j);
126                                 amount_expected = 0;
127                                 NextFrameSize();
128                                 return j;
129                         }
130                 }
131                 /* Not enough for a frame yet, COME AGAIN! */
132                 return 0;
133         }
134 };
135
136 /** Represents an zipped connections extra data
137  */
138 class izip_session : public classbase
139 {
140  public:
141         z_stream c_stream;      /* compression stream */
142         z_stream d_stream;      /* decompress stream */
143         izip_status status;     /* Connection status */
144         int fd;                 /* File descriptor */
145         CountedBuffer* inbuf;   /* Holds input buffer */
146         std::string outbuf;     /* Holds output buffer */
147 };
148
149 class ModuleZLib : public Module
150 {
151         izip_session sessions[MAX_DESCRIPTORS];
152
153         /* Used for stats z extensions */
154         float total_out_compressed;
155         float total_in_compressed;
156         float total_out_uncompressed;
157         float total_in_uncompressed;
158         
159  public:
160         
161         ModuleZLib(InspIRCd* Me)
162                 : Module::Module(Me)
163         {
164                 ServerInstance->PublishInterface("InspSocketHook", this);
165
166                 total_out_compressed = total_in_compressed = 0;
167                 total_out_uncompressed = total_out_uncompressed = 0;
168         }
169
170         virtual ~ModuleZLib()
171         {
172                 ServerInstance->UnpublishInterface("InspSocketHook", this);
173         }
174
175         virtual Version GetVersion()
176         {
177                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
178         }
179
180         void Implements(char* List)
181         {
182                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
183                 List[I_OnStats] = List[I_OnRequest] = 1;
184         }
185
186         /* Handle InspSocketHook API requests */
187         virtual char* OnRequest(Request* request)
188         {
189                 ISHRequest* ISR = (ISHRequest*)request;
190                 if (strcmp("IS_NAME", request->GetId()) == 0)
191                 {
192                         /* Return name */
193                         return "zip";
194                 }
195                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
196                 {
197                         /* Attach to an inspsocket */
198                         char* ret = "OK";
199                         try
200                         {
201                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
202                         }
203                         catch (ModuleException& e)
204                         {
205                                 return NULL;
206                         }
207                         return ret;
208                 }
209                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
210                 {
211                         /* Detatch from an inspsocket */
212                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
213                 }
214                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
215                 {
216                         /* Check for completion of handshake
217                          * (actually, this module doesnt handshake)
218                          */
219                         return "OK";
220                 }
221                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
222                 {
223                         /* Attach certificate data to the inspsocket
224                          * (this module doesnt do that, either)
225                          */
226                         return NULL;
227                 }
228                 return NULL;
229         }
230
231         /* Handle stats z (misc stats) */
232         virtual int OnStats(char symbol, userrec* user, string_list &results)
233         {
234                 if (symbol == 'z')
235                 {
236                         std::string sn = ServerInstance->Config->ServerName;
237
238                         /* Yeah yeah, i know, floats are ew.
239                          * We used them here because we'd be casting to float anyway to do this maths,
240                          * and also only floating point numbers can deal with the pretty large numbers
241                          * involved in the total throughput of a server over a large period of time.
242                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
243                          * can still hold more.
244                          */
245                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
246                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
247
248                         float total_compressed = total_in_compressed + total_out_compressed;
249                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
250
251                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
252
253                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
254
255                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
256                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
257                         sprintf(combined_ratio, "%3.2f%%", total_r);
258
259                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
260                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
261                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
262                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
263                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
264                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
265                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
266                         return 0;
267                 }
268
269                 return 0;
270         }
271
272         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
273         {
274                 izip_session* session = &sessions[fd];
275         
276                 /* allocate state and buffers */
277                 session->fd = fd;
278                 session->status = IZIP_OPEN;
279                 session->inbuf = new CountedBuffer();
280
281                 session->c_stream.zalloc = (alloc_func)0;
282                 session->c_stream.zfree = (free_func)0;
283                 session->c_stream.opaque = (voidpf)0;
284
285                 session->d_stream.zalloc = (alloc_func)0;
286                 session->d_stream.zfree = (free_func)0;
287                 session->d_stream.opaque = (voidpf)0;
288         }
289
290         virtual void OnRawSocketConnect(int fd)
291         {
292                 /* Nothing special needs doing here compared to accept() */
293                 OnRawSocketAccept(fd, "", 0);
294         }
295
296         virtual void OnRawSocketClose(int fd)
297         {
298                 CloseSession(&sessions[fd]);
299         }
300
301         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
302         {
303                 /* Find the sockets session */
304                 izip_session* session = &sessions[fd];
305
306                 if (session->status == IZIP_CLOSED)
307                         return 0;
308
309                 unsigned char compr[CHUNK + 4];
310                 unsigned int offset = 0;
311                 unsigned int total_size = 0;
312
313                 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
314                 readresult = read(fd, compr, CHUNK);
315
316                 /* Did we get anything? */
317                 if (readresult > 0)
318                 {
319                         /* Add it to the frame queue */
320                         session->inbuf->AddData(compr, readresult);
321                         total_in_compressed += readresult;
322         
323                         /* Parse all completed frames */
324                         int size = 0;
325                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
326                         {
327                                 session->d_stream.next_in  = (Bytef*)compr;
328                                 session->d_stream.avail_in = 0;
329                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
330
331                                 /* If we cant call this, well, we're boned. */
332                                 if (inflateInit(&session->d_stream) != Z_OK)
333                                         return 0;
334         
335                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
336                                 {
337                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
338                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
339                                                 break;
340                                 }
341         
342                                 /* Stick a fork in me, i'm done */
343                                 inflateEnd(&session->d_stream);
344
345                                 /* Update counters and offsets */
346                                 total_size += session->d_stream.total_out;
347                                 total_in_uncompressed += session->d_stream.total_out;
348                                 offset += session->d_stream.total_out;
349                         }
350
351                         /* Null-terminate the buffer -- this doesnt harm binary data */
352                         buffer[total_size] = 0;
353
354                         /* Set the read size to the correct total size */
355                         readresult = total_size;
356
357                 }
358                 return (readresult > 0);
359         }
360
361         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
362         {
363                 izip_session* session = &sessions[fd];
364                 int ocount = count;
365
366                 if (!count)     /* Nothing to do! */
367                         return 0;
368
369                 if(session->status != IZIP_OPEN)
370                 {
371                         /* Seriously, wtf? */
372                         CloseSession(session);
373                         return 0;
374                 }
375
376                 unsigned char compr[CHUNK + 4];
377
378                 /* Gentlemen, start your engines! */
379                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
380                 {
381                         CloseSession(session);
382                         return 0;
383                 }
384
385                 /* Set buffer sizes (we reserve 4 bytes at the start of the
386                  * buffer for the length counters)
387                  */
388                 session->c_stream.next_in  = (Bytef*)buffer;
389                 session->c_stream.next_out = compr + 4;
390
391                 /* Compress the text */
392                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
393                 {
394                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
395                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
396                         {
397                                 CloseSession(session);
398                                 return 0;
399                         }
400                 }
401                 /* Finish the stream */
402                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
403                 deflateEnd(&session->c_stream);
404
405                 total_out_uncompressed += ocount;
406                 total_out_compressed += session->c_stream.total_out;
407
408                 /** Assemble the frame length onto the frame, in network byte order */
409                 compr[0] = (session->c_stream.total_out >> 24);
410                 compr[1] = (session->c_stream.total_out >> 16);
411                 compr[2] = (session->c_stream.total_out >> 8);
412                 compr[3] = (session->c_stream.total_out & 0xFF);
413
414                 /* Add compressed data plus leading length to the output buffer -
415                  * Note, we may have incomplete half-sent frames in here.
416                  */
417                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
418
419                 /* Lets see how much we can send out */
420                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
421
422                 /* Check for errors, and advance the buffer if any was sent */
423                 if (ret > 0)
424                         session->outbuf = session->outbuf.substr(ret);
425                 else if (ret < 1)
426                 {
427                         if (ret == -1)
428                         {
429                                 if (errno == EAGAIN)
430                                         return 0;
431                                 else
432                                 {
433                                         session->outbuf = "";
434                                         return 0;
435                                 }
436                         }
437                         else
438                         {
439                                 session->outbuf = "";
440                                 return 0;
441                         }
442                 }
443
444                 /* ALL LIES the lot of it, we havent really written
445                  * this amount, but the layer above doesnt need to know.
446                  */
447                 return ocount;
448         }
449         
450         void CloseSession(izip_session* session)
451         {
452                 if (session->status = IZIP_OPEN)
453                 {
454                         session->status = IZIP_CLOSED;
455                         session->outbuf = "";
456                         delete session->inbuf;
457                 }
458         }
459
460 };
461
462 class ModuleZLibFactory : public ModuleFactory
463 {
464  public:
465         ModuleZLibFactory()
466         {
467         }
468         
469         ~ModuleZLibFactory()
470         {
471         }
472         
473         virtual Module * CreateModule(InspIRCd* Me)
474         {
475                 return new ModuleZLib(Me);
476         }
477 };
478
479
480 extern "C" void * init_module( void )
481 {
482         return new ModuleZLibFactory;
483 }