]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
756cf52230595ac386ee16c39658a5b452b23ee0
[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         }
173
174         virtual Version GetVersion()
175         {
176                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
177         }
178
179         void Implements(char* List)
180         {
181                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
182                 List[I_OnStats] = List[I_OnRequest] = 1;
183         }
184
185         /* Handle InspSocketHook API requests */
186         virtual char* OnRequest(Request* request)
187         {
188                 ISHRequest* ISR = (ISHRequest*)request;
189                 if (strcmp("IS_NAME", request->GetId()) == 0)
190                 {
191                         /* Return name */
192                         return "zip";
193                 }
194                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
195                 {
196                         /* Attach to an inspsocket */
197                         char* ret = "OK";
198                         try
199                         {
200                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
201                         }
202                         catch (ModuleException& e)
203                         {
204                                 return NULL;
205                         }
206                         return ret;
207                 }
208                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
209                 {
210                         /* Detatch from an inspsocket */
211                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
212                 }
213                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
214                 {
215                         /* Check for completion of handshake
216                          * (actually, this module doesnt handshake)
217                          */
218                         return "OK";
219                 }
220                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
221                 {
222                         /* Attach certificate data to the inspsocket
223                          * (this module doesnt do that, either)
224                          */
225                         return NULL;
226                 }
227                 return NULL;
228         }
229
230         /* Handle stats z (misc stats) */
231         virtual int OnStats(char symbol, userrec* user, string_list &results)
232         {
233                 if (symbol == 'z')
234                 {
235                         std::string sn = ServerInstance->Config->ServerName;
236
237                         /* Yeah yeah, i know, floats are ew.
238                          * We used them here because we'd be casting to float anyway to do this maths,
239                          * and also only floating point numbers can deal with the pretty large numbers
240                          * involved in the total throughput of a server over a large period of time.
241                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
242                          * can still hold more.
243                          */
244                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
245                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
246
247                         float total_compressed = total_in_compressed + total_out_compressed;
248                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
249
250                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
251
252                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
253
254                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
255                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
256                         sprintf(combined_ratio, "%3.2f%%", total_r);
257
258                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
259                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
260                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
261                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
262                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
263                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
264                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
265                         return 0;
266                 }
267
268                 return 0;
269         }
270
271         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
272         {
273                 izip_session* session = &sessions[fd];
274         
275                 /* allocate state and buffers */
276                 session->fd = fd;
277                 session->status = IZIP_OPEN;
278                 session->inbuf = new CountedBuffer();
279
280                 session->c_stream.zalloc = (alloc_func)0;
281                 session->c_stream.zfree = (free_func)0;
282                 session->c_stream.opaque = (voidpf)0;
283
284                 session->d_stream.zalloc = (alloc_func)0;
285                 session->d_stream.zfree = (free_func)0;
286                 session->d_stream.opaque = (voidpf)0;
287         }
288
289         virtual void OnRawSocketConnect(int fd)
290         {
291                 /* Nothing special needs doing here compared to accept() */
292                 OnRawSocketAccept(fd, "", 0);
293         }
294
295         virtual void OnRawSocketClose(int fd)
296         {
297                 CloseSession(&sessions[fd]);
298         }
299
300         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
301         {
302                 /* Find the sockets session */
303                 izip_session* session = &sessions[fd];
304
305                 if (session->status == IZIP_CLOSED)
306                         return 0;
307
308                 unsigned char compr[CHUNK + 4];
309                 unsigned int offset = 0;
310                 unsigned int total_size = 0;
311
312                 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
313                 readresult = read(fd, compr, CHUNK);
314
315                 /* Did we get anything? */
316                 if (readresult > 0)
317                 {
318                         /* Add it to the frame queue */
319                         session->inbuf->AddData(compr, readresult);
320         
321                         /* Parse all completed frames */
322                         int size = 0;
323                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
324                         {
325                                 session->d_stream.next_in  = (Bytef*)compr;
326                                 session->d_stream.avail_in = 0;
327                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
328
329                                 if (inflateInit(&session->d_stream) != Z_OK)
330                                         return -EBADF;
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                                 inflateEnd(&session->d_stream);
340
341                                 total_in_compressed += readresult;
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                         buffer[total_size] = 0;
348                         readresult = total_size;
349
350                 }
351                 return (readresult > 0);
352         }
353
354         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
355         {
356                 izip_session* session = &sessions[fd];
357                 int ocount = count;
358
359                 if (!count)     /* Nothing to do! */
360                         return 0;
361
362                 if(session->status != IZIP_OPEN)
363                 {
364                         /* Seriously, wtf? */
365                         CloseSession(session);
366                         return 0;
367                 }
368
369                 unsigned char compr[CHUNK + 4];
370
371                 /* Gentlemen, start your engines! */
372                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
373                 {
374                         CloseSession(session);
375                         return 0;
376                 }
377
378                 /* Set buffer sizes (we reserve 4 bytes at the start of the
379                  * buffer for the length counters)
380                  */
381                 session->c_stream.next_in  = (Bytef*)buffer;
382                 session->c_stream.next_out = compr + 4;
383
384                 /* Compress the text */
385                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
386                 {
387                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
388                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
389                         {
390                                 CloseSession(session);
391                                 return 0;
392                         }
393                 }
394                 /* Finish the stream */
395                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
396                 deflateEnd(&session->c_stream);
397
398                 total_out_uncompressed += ocount;
399                 total_out_compressed += session->c_stream.total_out;
400
401                 /** Assemble the frame length onto the frame, in network byte order */
402                 compr[0] = (session->c_stream.total_out >> 24);
403                 compr[1] = (session->c_stream.total_out >> 16);
404                 compr[2] = (session->c_stream.total_out >> 8);
405                 compr[3] = (session->c_stream.total_out & 0xFF);
406
407                 /* Add compressed data plus leading length to the output buffer -
408                  * Note, we may have incomplete half-sent frames in here.
409                  */
410                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
411
412                 /* Lets see how much we can send out */
413                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
414
415                 /* Check for errors, and advance the buffer if any was sent */
416                 if (ret > 0)
417                         session->outbuf = session->outbuf.substr(ret);
418                 else if (ret < 1)
419                 {
420                         if (ret == -1)
421                         {
422                                 if (errno == EAGAIN)
423                                         return 0;
424                                 else
425                                 {
426                                         session->outbuf = "";
427                                         return 0;
428                                 }
429                         }
430                         else
431                         {
432                                 session->outbuf = "";
433                                 return 0;
434                         }
435                 }
436
437                 /* ALL LIES the lot of it, we havent really written
438                  * this amount, but the layer above doesnt need to know.
439                  */
440                 return ocount;
441         }
442         
443         void CloseSession(izip_session* session)
444         {
445                 if (session->status = IZIP_OPEN)
446                 {
447                         session->status = IZIP_CLOSED;
448                         session->outbuf = "";
449                         delete session->inbuf;
450                 }
451         }
452
453 };
454
455 class ModuleZLibFactory : public ModuleFactory
456 {
457  public:
458         ModuleZLibFactory()
459         {
460         }
461         
462         ~ModuleZLibFactory()
463         {
464         }
465         
466         virtual Module * CreateModule(InspIRCd* Me)
467         {
468                 return new ModuleZLib(Me);
469         }
470 };
471
472
473 extern "C" void * init_module( void )
474 {
475         return new ModuleZLibFactory;
476 }