]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
dfad2d0e08f786ac36a5d748ef86824a2dc13c0e
[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 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
60
61 const unsigned int CHUNK = 128 * 1024;
62
63 class CountedBuffer : public classbase
64 {
65         std::string buffer;             /* Current buffer contents */
66         unsigned int amount_expected;   /* Amount of data expected */
67  public:
68         CountedBuffer()
69         {
70                 amount_expected = 0;
71         }
72
73         /** Adds arbitrary compressed data to the buffer.
74          * - Binsry safe, of course.
75          */
76         void AddData(unsigned char* data, int data_length)
77         {
78                 buffer.append((const char*)data, data_length);
79                 this->NextFrameSize();
80         }
81
82         /** Works out the size of the next compressed frame
83          */
84         void NextFrameSize()
85         {
86                 if ((!amount_expected) && (buffer.length() >= 4))
87                 {
88                         /* We have enough to read an int -
89                          * Yes, this is safe, but its ugly. Give me
90                          * a nicer way to read 4 bytes from a binary
91                          * stream, and push them into a 32 bit int,
92                          * and i'll consider replacing this.
93                          */
94                         amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
95                         buffer = buffer.substr(4);
96                 }
97         }
98
99         /** Gets the next frame and returns its size, or returns
100          * zero if there isnt one available yet.
101          * A frame can contain multiple plaintext lines.
102          * - Binary safe.
103          */
104         int GetFrame(unsigned char* frame, int maxsize)
105         {
106                 if (amount_expected)
107                 {
108                         /* We know how much we're expecting...
109                          * Do we have enough yet?
110                          */
111                         if (buffer.length() >= amount_expected)
112                         {
113                                 int j = 0;
114                                 for (unsigned int i = 0; i < amount_expected; i++, j++)
115                                         frame[i] = buffer[i];
116
117                                 buffer = buffer.substr(j);
118                                 amount_expected = 0;
119                                 NextFrameSize();
120                                 return j;
121                         }
122                 }
123                 /* Not enough for a frame yet, COME AGAIN! */
124                 return 0;
125         }
126 };
127
128 /** Represents an zipped connections extra data
129  */
130 class izip_session : public classbase
131 {
132  public:
133         z_stream c_stream; /* compression stream */
134         z_stream d_stream; /* decompress stream */
135         izip_status status;
136         int fd;
137         CountedBuffer* inbuf;
138         std::string outbuf;
139 };
140
141 class ModuleZLib : public Module
142 {
143         izip_session sessions[MAX_DESCRIPTORS];
144
145         /* Used for stats z extensions */
146         float total_out_compressed;
147         float total_in_compressed;
148         float total_out_uncompressed;
149         float total_in_uncompressed;
150         
151  public:
152         
153         ModuleZLib(InspIRCd* Me)
154                 : Module::Module(Me)
155         {
156                 ServerInstance->PublishInterface("InspSocketHook", this);
157
158                 total_out_compressed = total_in_compressed = 0;
159                 total_out_uncompressed = total_out_uncompressed = 0;
160         }
161
162         virtual ~ModuleZLib()
163         {
164         }
165
166         virtual Version GetVersion()
167         {
168                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
169         }
170
171         void Implements(char* List)
172         {
173                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
174                 List[I_OnStats] = List[I_OnRequest] = 1;
175         }
176
177         /* Handle InspSocketHook API requests */
178         virtual char* OnRequest(Request* request)
179         {
180                 ISHRequest* ISR = (ISHRequest*)request;
181                 if (strcmp("IS_NAME", request->GetId()) == 0)
182                 {
183                         return "zip";
184                 }
185                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
186                 {
187                         char* ret = "OK";
188                         try
189                         {
190                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
191                         }
192                         catch (ModuleException& e)
193                         {
194                                 return NULL;
195                         }
196                         return ret;
197                 }
198                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
199                 {
200                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
201                 }
202                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
203                 {
204                         return "OK";
205                 }
206                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
207                 {
208                         return NULL;
209                 }
210                 return NULL;
211         }
212
213         /* Handle stats z (misc stats) */
214         virtual int OnStats(char symbol, userrec* user, string_list &results)
215         {
216                 if (symbol == 'z')
217                 {
218                         std::string sn = ServerInstance->Config->ServerName;
219
220                         /* Yeah yeah, i know, floats are ew.
221                          * We used them here because we'd be casting to float anyway to do this maths,
222                          * and also only floating point numbers can deal with the pretty large numbers
223                          * involved in the total throughput of a server over a large period of time.
224                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
225                          * can still hold more.
226                          */
227                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
228                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
229
230                         float total_compressed = total_in_compressed + total_out_compressed;
231                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
232
233                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
234
235                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
236
237                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
238                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
239                         sprintf(combined_ratio, "%3.2f%%", total_r);
240
241                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
242                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
243                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
244                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
245                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
246                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
247                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
248                         return 0;
249                 }
250
251                 return 0;
252         }
253
254         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
255         {
256                 izip_session* session = &sessions[fd];
257         
258                 /* allocate state and buffers */
259                 session->fd = fd;
260                 session->status = IZIP_OPEN;
261                 session->inbuf = new CountedBuffer();
262
263                 session->c_stream.zalloc = (alloc_func)0;
264                 session->c_stream.zfree = (free_func)0;
265                 session->c_stream.opaque = (voidpf)0;
266
267                 session->d_stream.zalloc = (alloc_func)0;
268                 session->d_stream.zfree = (free_func)0;
269                 session->d_stream.opaque = (voidpf)0;
270         }
271
272         virtual void OnRawSocketConnect(int fd)
273         {
274                 /* Nothing special needs doing here compared to accept() */
275                 OnRawSocketAccept(fd, "", 0);
276         }
277
278         virtual void OnRawSocketClose(int fd)
279         {
280                 CloseSession(&sessions[fd]);
281         }
282
283         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
284         {
285                 /* Find the sockets session */
286                 izip_session* session = &sessions[fd];
287
288                 if (session->status == IZIP_CLOSED)
289                         return 0;
290
291                 unsigned char compr[CHUNK + 4];
292                 unsigned int offset = 0;
293                 unsigned int total_size = 0;
294
295                 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
296                 readresult = read(fd, compr, CHUNK);
297
298                 /* Did we get anything? */
299                 if (readresult > 0)
300                 {
301                         /* Add it to the frame queue */
302                         session->inbuf->AddData(compr, readresult);
303         
304                         /* Parse all completed frames */
305                         int size = 0;
306                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
307                         {
308                                 session->d_stream.next_in  = (Bytef*)compr;
309                                 session->d_stream.avail_in = 0;
310                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
311
312                                 if (inflateInit(&session->d_stream) != Z_OK)
313                                         return -EBADF;
314         
315                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
316                                 {
317                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
318                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
319                                                 break;
320                                 }
321         
322                                 inflateEnd(&session->d_stream);
323
324                                 total_in_compressed += readresult;
325                                 total_size += session->d_stream.total_out;
326                                 total_in_uncompressed += session->d_stream.total_out;
327                                 offset += session->d_stream.total_out;
328                         }
329
330                         buffer[total_size] = 0;
331                         readresult = total_size;
332
333                 }
334                 return (readresult > 0);
335         }
336
337         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
338         {
339                 izip_session* session = &sessions[fd];
340                 int ocount = count;
341
342                 if (!count)
343                         return 0;
344         
345                 if(session->status != IZIP_OPEN)
346                 {
347                         CloseSession(session);
348                         return 0;
349                 }
350
351                 unsigned char compr[CHUNK + 4];
352
353                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
354                 {
355                         CloseSession(session);
356                         return 0;
357                 }
358
359                 session->c_stream.next_in  = (Bytef*)buffer;
360                 session->c_stream.next_out = compr + 4;
361
362                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
363                 {
364                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
365                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
366                         {
367                                 CloseSession(session);
368                                 return 0;
369                         }
370                 }
371                 /* Finish the stream */
372                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
373                 deflateEnd(&session->c_stream);
374
375                 total_out_uncompressed += ocount;
376                 total_out_compressed += session->c_stream.total_out;
377
378                 /** Assemble the frame length onto the frame, in network byte order */
379                 compr[0] = (session->c_stream.total_out >> 24);
380                 compr[1] = (session->c_stream.total_out >> 16);
381                 compr[2] = (session->c_stream.total_out >> 8);
382                 compr[3] = (session->c_stream.total_out & 0xFF);
383
384                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
385
386                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
387
388                 if (ret > 0)
389                         session->outbuf = session->outbuf.substr(ret);
390                 else if (ret < 1)
391                 {
392                         if (ret == -1)
393                         {
394                                 if (errno == EAGAIN)
395                                         return 0;
396                                 else
397                                 {
398                                         session->outbuf = "";
399                                         return 0;
400                                 }
401                         }
402                         else
403                         {
404                                 session->outbuf = "";
405                                 return 0;
406                         }
407                 }
408
409                 /* ALL LIES the lot of it, we havent really written
410                  * this amount, but the layer above doesnt need to know.
411                  */
412                 return ocount;
413         }
414         
415         void CloseSession(izip_session* session)
416         {
417                 if (session->status = IZIP_OPEN)
418                 {
419                         session->status = IZIP_CLOSED;
420                         session->outbuf = "";
421                         delete session->inbuf;
422                 }
423         }
424
425 };
426
427 class ModuleZLibFactory : public ModuleFactory
428 {
429  public:
430         ModuleZLibFactory()
431         {
432         }
433         
434         ~ModuleZLibFactory()
435         {
436         }
437         
438         virtual Module * CreateModule(InspIRCd* Me)
439         {
440                 return new ModuleZLib(Me);
441         }
442 };
443
444
445 extern "C" void * init_module( void )
446 {
447         return new ModuleZLibFactory;
448 }