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