]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
This is better now.
[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         void AddData(unsigned char* data, int data_length)
74         {
75                 //printf("ADDDATA\n");
76                 buffer.append((const char*)data, data_length);
77                 this->NextFrameSize();
78                 //printf("SIZE=%d %d\n",buffer.length(), data_length);
79         }
80
81         void NextFrameSize()
82         {
83                 if ((!amount_expected) && (buffer.length() >= 4))
84                 {
85                         /* We have enough to read an int -
86                          * Yes, this is safe, but its ugly. Give me
87                          * a nicer way to read 4 bytes from a binary
88                          * stream, and push them into a 32 bit int,
89                          * and i'll consider replacing this.
90                          */
91                         amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
92                         //printf("EXPECT: %02x %02x %02x %02x\n", buffer[0], buffer[1], buffer[2], buffer[3]);
93                         buffer = buffer.substr(4);
94                         //printf("NEXTFRAME FS=%d SIZE=%d\n",amount_expected, buffer.length());
95                 }
96         }
97
98         int GetFrame(unsigned char* frame, int maxsize)
99         {
100                 if (amount_expected)
101                 {
102                         /* We know how much we're expecting...
103                          * Do we have enough yet?
104                          */
105                         if (buffer.length() >= amount_expected)
106                         {
107                                 int j = 0;
108                                 for (unsigned int i = 0; i < amount_expected; i++, j++)
109                                         frame[i] = buffer[i];
110
111                                 buffer = buffer.substr(j);
112                                 amount_expected = 0;
113                                 NextFrameSize();
114                                 return j;
115                         }
116                 }
117                 /* Not enough for a frame yet, COME AGAIN! */
118                 return 0;
119         }
120 };
121
122 /** Represents an ZIP user's extra data
123  */
124 class izip_session : public classbase
125 {
126  public:
127         z_stream c_stream; /* compression stream */
128         z_stream d_stream; /* decompress stream */
129         izip_status status;
130         int fd;
131         CountedBuffer* inbuf;
132         std::string outbuf;
133 };
134
135 class ModuleZLib : public Module
136 {
137         izip_session sessions[MAX_DESCRIPTORS];
138         float total_out_compressed;
139         float total_in_compressed;
140         float total_out_uncompressed;
141         float total_in_uncompressed;
142         
143  public:
144         
145         ModuleZLib(InspIRCd* Me)
146                 : Module::Module(Me)
147         {
148                 ServerInstance->PublishInterface("InspSocketHook", this);
149
150                 total_out_compressed = total_in_compressed = 0;
151                 total_out_uncompressed = total_out_uncompressed = 0;
152         }
153
154         virtual ~ModuleZLib()
155         {
156         }
157
158         virtual Version GetVersion()
159         {
160                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
161         }
162
163         void Implements(char* List)
164         {
165                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
166                 List[I_OnStats] = List[I_OnRequest] = 1;
167         }
168
169         virtual char* OnRequest(Request* request)
170         {
171                 ISHRequest* ISR = (ISHRequest*)request;
172                 if (strcmp("IS_NAME", request->GetId()) == 0)
173                 {
174                         return "zip";
175                 }
176                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
177                 {
178                         char* ret = "OK";
179                         try
180                         {
181                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
182                         }
183                         catch (ModuleException& e)
184                         {
185                                 return NULL;
186                         }
187                         return ret;
188                 }
189                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
190                 {
191                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
192                 }
193                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
194                 {
195                         return "OK";
196                 }
197                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
198                 {
199                         return NULL;
200                 }
201                 return NULL;
202         }
203
204         virtual int OnStats(char symbol, userrec* user, string_list &results)
205         {
206                 if (symbol == 'z')
207                 {
208                         std::string sn = ServerInstance->Config->ServerName;
209
210                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
211                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
212
213                         float total_compressed = total_in_compressed + total_out_compressed;
214                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
215
216                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
217
218                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
219
220                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
221                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
222                         sprintf(combined_ratio, "%3.2f%%", total_r);
223
224                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
225                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
226                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
227                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
228                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
229                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
230                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
231                         return 0;
232                 }
233
234                 return 0;
235         }
236
237         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
238         {
239                 izip_session* session = &sessions[fd];
240         
241                 /* allocate deflate state */
242                 session->fd = fd;
243                 session->status = IZIP_OPEN;
244
245                 session->inbuf = new CountedBuffer();
246                 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
247
248                 session->c_stream.zalloc = (alloc_func)0;
249                 session->c_stream.zfree = (free_func)0;
250                 session->c_stream.opaque = (voidpf)0;
251
252                 session->d_stream.zalloc = (alloc_func)0;
253                 session->d_stream.zfree = (free_func)0;
254                 session->d_stream.opaque = (voidpf)0;
255         }
256
257         virtual void OnRawSocketConnect(int fd)
258         {
259                 OnRawSocketAccept(fd, "", 0);
260         }
261
262         virtual void OnRawSocketClose(int fd)
263         {
264                 CloseSession(&sessions[fd]);
265         }
266
267         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
268         {
269                 izip_session* session = &sessions[fd];
270
271                 if (session->status == IZIP_CLOSED)
272                         return 1;
273
274                 unsigned char compr[CHUNK + 1];
275
276                 readresult = read(fd, compr, CHUNK);
277
278                 if (readresult > 0)
279                 {
280                         session->inbuf->AddData(compr, readresult);
281         
282                         int size = 0;
283                         std::string str_out;
284                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
285                         {
286                                 unsigned char localbuf[count + 1];
287
288                                 session->d_stream.next_in  = (Bytef*)compr;
289                                 session->d_stream.avail_in = 0;
290                                 session->d_stream.next_out = (Bytef*)localbuf;
291                                 if (inflateInit(&session->d_stream) != Z_OK)
292                                         return -EBADF;
293         
294                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
295                                 {
296                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
297                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
298                                                 break;
299                                 }
300         
301                                 inflateEnd(&session->d_stream);
302
303                                 localbuf[session->d_stream.total_out] = 0;
304                                 str_out.append((const char*)localbuf);
305                                 total_in_compressed += readresult;
306                                 readresult = session->d_stream.total_out;
307                                 total_in_uncompressed += session->d_stream.total_out;
308                         }
309
310                         memcpy(buffer, str_out.data(), str_out.length() > count ? count : str_out.length());
311                         readresult = str_out.length();
312                 }
313                 return (readresult > 0);
314         }
315
316         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
317         {
318                 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
319
320                 izip_session* session = &sessions[fd];
321                 int ocount = count;
322
323                 if (!count)
324                 {
325                         ServerInstance->Log(DEBUG,"Nothing to do!");
326                         return 1;
327                 }
328
329                 if(session->status != IZIP_OPEN)
330                 {
331                         CloseSession(session);
332                         return 0;
333                 }
334
335                 unsigned char compr[CHUNK];
336
337                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
338                 {
339                         ServerInstance->Log(DEBUG,"Deflate init failed");
340                 }
341
342                 session->c_stream.next_in  = (Bytef*)buffer;
343                 session->c_stream.next_out = compr+4;
344
345                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
346                 {
347                         session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
348                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
349                         {
350                                 ServerInstance->Log(DEBUG,"Couldnt deflate!");
351                                 CloseSession(session);
352                                 return 0;
353                         }
354                 }
355                 /* Finish the stream, still forcing small buffers: */
356                 for (;;)
357                 {
358                         session->c_stream.avail_out = 1;
359                         if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
360                                 break;
361                 }
362
363                 deflateEnd(&session->c_stream);
364
365                 total_out_uncompressed += ocount;
366                 total_out_compressed += session->c_stream.total_out;
367
368                 int x = htonl(session->c_stream.total_out);
369                 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
370                  * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
371                  * assembling the frame size into the same packet as the compressed frame.
372                  */
373                 memcpy(compr, &x, sizeof(x));
374
375                 session->outbuf.append((const char*)compr, session->c_stream.total_out+4);
376
377                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
378
379                 if (ret > 0)
380                         session->outbuf = session->outbuf.substr(ret);
381                 else if (ret < 1)
382                 {
383                         if (ret == -1)
384                                 return errno == EAGAIN;
385                         else
386                         {
387                                 session->outbuf = "";
388                                 return 0;
389                         }
390                 }
391
392                 ServerInstance->Log(DEBUG,"Sending frame of size %d", ntohl(x));
393
394                 /* ALL LIES the lot of it, we havent really written
395                  * this amount, but the layer above doesnt need to know.
396                  */
397                 return ocount;
398         }
399         
400         void CloseSession(izip_session* session)
401         {
402                 if (session->status = IZIP_OPEN)
403                 {
404                         session->status = IZIP_CLOSED;
405                         session->outbuf = "";
406                         delete session->inbuf;
407                 }
408         }
409
410 };
411
412 class ModuleZLibFactory : public ModuleFactory
413 {
414  public:
415         ModuleZLibFactory()
416         {
417         }
418         
419         ~ModuleZLibFactory()
420         {
421         }
422         
423         virtual Module * CreateModule(InspIRCd* Me)
424         {
425                 return new ModuleZLib(Me);
426         }
427 };
428
429
430 extern "C" void * init_module( void )
431 {
432         return new ModuleZLibFactory;
433 }