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