]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
Change how assembling of multiple lines works, avoid data copies
[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 ZIP user's 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         float total_out_compressed;
145         float total_in_compressed;
146         float total_out_uncompressed;
147         float total_in_uncompressed;
148         
149  public:
150         
151         ModuleZLib(InspIRCd* Me)
152                 : Module::Module(Me)
153         {
154                 ServerInstance->PublishInterface("InspSocketHook", this);
155
156                 total_out_compressed = total_in_compressed = 0;
157                 total_out_uncompressed = total_out_uncompressed = 0;
158         }
159
160         virtual ~ModuleZLib()
161         {
162         }
163
164         virtual Version GetVersion()
165         {
166                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
167         }
168
169         void Implements(char* List)
170         {
171                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
172                 List[I_OnStats] = List[I_OnRequest] = 1;
173         }
174
175         virtual char* OnRequest(Request* request)
176         {
177                 ISHRequest* ISR = (ISHRequest*)request;
178                 if (strcmp("IS_NAME", request->GetId()) == 0)
179                 {
180                         return "zip";
181                 }
182                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
183                 {
184                         char* ret = "OK";
185                         try
186                         {
187                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
188                         }
189                         catch (ModuleException& e)
190                         {
191                                 return NULL;
192                         }
193                         return ret;
194                 }
195                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
196                 {
197                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
198                 }
199                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
200                 {
201                         return "OK";
202                 }
203                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
204                 {
205                         return NULL;
206                 }
207                 return NULL;
208         }
209
210         virtual int OnStats(char symbol, userrec* user, string_list &results)
211         {
212                 if (symbol == 'z')
213                 {
214                         std::string sn = ServerInstance->Config->ServerName;
215
216                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
217                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
218
219                         float total_compressed = total_in_compressed + total_out_compressed;
220                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
221
222                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
223
224                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
225
226                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
227                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
228                         sprintf(combined_ratio, "%3.2f%%", total_r);
229
230                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
231                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
232                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
233                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
234                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
235                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
236                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
237                         return 0;
238                 }
239
240                 return 0;
241         }
242
243         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
244         {
245                 izip_session* session = &sessions[fd];
246         
247                 /* allocate deflate state */
248                 session->fd = fd;
249                 session->status = IZIP_OPEN;
250
251                 session->inbuf = new CountedBuffer();
252                 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
253
254                 session->c_stream.zalloc = (alloc_func)0;
255                 session->c_stream.zfree = (free_func)0;
256                 session->c_stream.opaque = (voidpf)0;
257
258                 session->d_stream.zalloc = (alloc_func)0;
259                 session->d_stream.zfree = (free_func)0;
260                 session->d_stream.opaque = (voidpf)0;
261         }
262
263         virtual void OnRawSocketConnect(int fd)
264         {
265                 OnRawSocketAccept(fd, "", 0);
266         }
267
268         virtual void OnRawSocketClose(int fd)
269         {
270                 CloseSession(&sessions[fd]);
271         }
272
273         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
274         {
275                 izip_session* session = &sessions[fd];
276
277                 if (session->status == IZIP_CLOSED)
278                         return 1;
279
280                 unsigned char compr[CHUNK + 1];
281                 unsigned int offset = 0;
282                 unsigned int total_size = 0;
283
284                 readresult = read(fd, compr, CHUNK);
285
286                 if (readresult > 0)
287                 {
288                         session->inbuf->AddData(compr, readresult);
289         
290                         int size = 0;
291                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
292                         {
293                                 session->d_stream.next_in  = (Bytef*)compr;
294                                 session->d_stream.avail_in = 0;
295                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
296                                 if (inflateInit(&session->d_stream) != Z_OK)
297                                         return -EBADF;
298         
299                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
300                                 {
301                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
302                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
303                                                 break;
304                                 }
305         
306                                 inflateEnd(&session->d_stream);
307
308                                 total_in_compressed += readresult;
309                                 total_size += session->d_stream.total_out;
310                                 readresult = session->d_stream.total_out;
311                                 total_in_uncompressed += session->d_stream.total_out;
312                         }
313
314                         buffer[total_size] = 0;
315
316                 }
317                 return (readresult > 0);
318         }
319
320         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
321         {
322                 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
323
324                 izip_session* session = &sessions[fd];
325                 int ocount = count;
326
327                 if (!count)
328                 {
329                         ServerInstance->Log(DEBUG,"Nothing to do!");
330                         return 1;
331                 }
332
333                 if(session->status != IZIP_OPEN)
334                 {
335                         CloseSession(session);
336                         return -1;
337                 }
338
339                 unsigned char compr[CHUNK];
340
341                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
342                 {
343                         ServerInstance->Log(DEBUG,"Deflate init failed");
344                 }
345
346                 session->c_stream.next_in  = (Bytef*)buffer;
347                 session->c_stream.next_out = compr+4;
348
349                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
350                 {
351                         session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
352                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
353                         {
354                                 ServerInstance->Log(DEBUG,"Couldnt deflate!");
355                                 CloseSession(session);
356                                 return 0;
357                         }
358                 }
359                 /* Finish the stream, still forcing small buffers: */
360                 for (;;)
361                 {
362                         session->c_stream.avail_out = 1;
363                         if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
364                                 break;
365                 }
366
367                 deflateEnd(&session->c_stream);
368
369                 total_out_uncompressed += ocount;
370                 total_out_compressed += session->c_stream.total_out;
371
372                 int x = htonl(session->c_stream.total_out);
373                 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
374                  * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
375                  * assembling the frame size into the same packet as the compressed frame.
376                  */
377                 memcpy(compr, &x, sizeof(x));
378
379                 session->outbuf.append((const char*)compr, session->c_stream.total_out+4);
380
381                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
382
383                 if (ret > 0)
384                         session->outbuf = session->outbuf.substr(ret);
385                 else if (ret < 1)
386                 {
387                         if (ret == -1)
388                         {
389                                 if (errno == EAGAIN)
390                                         return 0;
391                                 else
392                                 {
393                                         session->outbuf = "";
394                                         return -1;
395                                 }
396                         }
397                         else
398                         {
399                                 session->outbuf = "";
400                                 return -1;
401                         }
402                 }
403
404                 ServerInstance->Log(DEBUG,"Sending frame of size %d", ntohl(x));
405
406                 /* ALL LIES the lot of it, we havent really written
407                  * this amount, but the layer above doesnt need to know.
408                  */
409                 return ocount;
410         }
411         
412         void CloseSession(izip_session* session)
413         {
414                 if (session->status = IZIP_OPEN)
415                 {
416                         session->status = IZIP_CLOSED;
417                         session->outbuf = "";
418                         delete session->inbuf;
419                 }
420         }
421
422 };
423
424 class ModuleZLibFactory : public ModuleFactory
425 {
426  public:
427         ModuleZLibFactory()
428         {
429         }
430         
431         ~ModuleZLibFactory()
432         {
433         }
434         
435         virtual Module * CreateModule(InspIRCd* Me)
436         {
437                 return new ModuleZLib(Me);
438         }
439 };
440
441
442 extern "C" void * init_module( void )
443 {
444         return new ModuleZLibFactory;
445 }