]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
479eaa12ede87972124827276b7e4ecdc1beda9c
[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         
322                         /* Parse all completed frames */
323                         int size = 0;
324                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
325                         {
326                                 session->d_stream.next_in  = (Bytef*)compr;
327                                 session->d_stream.avail_in = 0;
328                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
329
330                                 if (inflateInit(&session->d_stream) != Z_OK)
331                                         return -EBADF;
332         
333                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
334                                 {
335                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
336                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
337                                                 break;
338                                 }
339         
340                                 inflateEnd(&session->d_stream);
341
342                                 total_in_compressed += readresult;
343                                 total_size += session->d_stream.total_out;
344                                 total_in_uncompressed += session->d_stream.total_out;
345                                 offset += session->d_stream.total_out;
346                         }
347
348                         buffer[total_size] = 0;
349                         readresult = total_size;
350
351                 }
352                 return (readresult > 0);
353         }
354
355         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
356         {
357                 izip_session* session = &sessions[fd];
358                 int ocount = count;
359
360                 if (!count)     /* Nothing to do! */
361                         return 0;
362
363                 if(session->status != IZIP_OPEN)
364                 {
365                         /* Seriously, wtf? */
366                         CloseSession(session);
367                         return 0;
368                 }
369
370                 unsigned char compr[CHUNK + 4];
371
372                 /* Gentlemen, start your engines! */
373                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
374                 {
375                         CloseSession(session);
376                         return 0;
377                 }
378
379                 /* Set buffer sizes (we reserve 4 bytes at the start of the
380                  * buffer for the length counters)
381                  */
382                 session->c_stream.next_in  = (Bytef*)buffer;
383                 session->c_stream.next_out = compr + 4;
384
385                 /* Compress the text */
386                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
387                 {
388                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
389                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
390                         {
391                                 CloseSession(session);
392                                 return 0;
393                         }
394                 }
395                 /* Finish the stream */
396                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
397                 deflateEnd(&session->c_stream);
398
399                 total_out_uncompressed += ocount;
400                 total_out_compressed += session->c_stream.total_out;
401
402                 /** Assemble the frame length onto the frame, in network byte order */
403                 compr[0] = (session->c_stream.total_out >> 24);
404                 compr[1] = (session->c_stream.total_out >> 16);
405                 compr[2] = (session->c_stream.total_out >> 8);
406                 compr[3] = (session->c_stream.total_out & 0xFF);
407
408                 /* Add compressed data plus leading length to the output buffer -
409                  * Note, we may have incomplete half-sent frames in here.
410                  */
411                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
412
413                 /* Lets see how much we can send out */
414                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
415
416                 /* Check for errors, and advance the buffer if any was sent */
417                 if (ret > 0)
418                         session->outbuf = session->outbuf.substr(ret);
419                 else if (ret < 1)
420                 {
421                         if (ret == -1)
422                         {
423                                 if (errno == EAGAIN)
424                                         return 0;
425                                 else
426                                 {
427                                         session->outbuf = "";
428                                         return 0;
429                                 }
430                         }
431                         else
432                         {
433                                 session->outbuf = "";
434                                 return 0;
435                         }
436                 }
437
438                 /* ALL LIES the lot of it, we havent really written
439                  * this amount, but the layer above doesnt need to know.
440                  */
441                 return ocount;
442         }
443         
444         void CloseSession(izip_session* session)
445         {
446                 if (session->status = IZIP_OPEN)
447                 {
448                         session->status = IZIP_CLOSED;
449                         session->outbuf = "";
450                         delete session->inbuf;
451                 }
452         }
453
454 };
455
456 class ModuleZLibFactory : public ModuleFactory
457 {
458  public:
459         ModuleZLibFactory()
460         {
461         }
462         
463         ~ModuleZLibFactory()
464         {
465         }
466         
467         virtual Module * CreateModule(InspIRCd* Me)
468         {
469                 return new ModuleZLib(Me);
470         }
471 };
472
473
474 extern "C" void * init_module( void )
475 {
476         return new ModuleZLibFactory;
477 }