]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
06ad20d35e5d6d339b67edcf10a35044438e84af
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 #include <string>
2 #include <vector>
3
4 #include "zlib.h"
5
6 #include "inspircd_config.h"
7 #include "configreader.h"
8 #include "users.h"
9 #include "channels.h"
10 #include "modules.h"
11
12 #include "socket.h"
13 #include "hashcomp.h"
14 #include "inspircd.h"
15
16 #include "transport.h"
17
18 /* $ModDesc: Provides zlib link support for servers */
19 /* $LinkerFlags: -lz */
20 /* $ModDep: transport.h */
21
22 /*
23  * Compressed data is transmitted across the link in the following format:
24  *
25  *   0   1   2   3   4 ... n
26  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
27  * |       n       |              Z0 -> Zn                         |
28  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
29  *
30  * Where: n is the size of a frame, in network byte order, 4 bytes.
31  * Z0 through Zn are Zlib compressed data, n bytes in length.
32  *
33  * If the module fails to read the entire frame, then it will buffer
34  * the portion of the last frame it received, then attempt to read
35  * the next part of the frame next time a write notification arrives.
36  *
37  * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
38  * a flush after each frame. A frame may contain multiple lines
39  * and should be treated as raw binary data.
40  *
41  */
42
43 static InspIRCd* SI;
44
45 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
46
47 const unsigned int CHUNK = 128 * 1024;
48
49 class CountedBuffer : public classbase
50 {
51         int bufptr;            /* Current tail location */
52         unsigned char* buffer; /* Current buffer contents */
53         int bufsz;             /* Current buffer size */
54         int amount_expected;   /* Amount of data expected */
55         int amount_read;       /* Amount of data read so far */
56  public:
57         CountedBuffer()
58         {
59                 bufsz = 1024;
60                 buffer = new unsigned char[bufsz + 1];
61                 bufptr = 0;
62                 amount_read = 0;
63                 amount_expected = 0;
64         }
65
66         ~CountedBuffer()
67         {
68                 delete[] buffer;
69         }
70
71         void AddData(unsigned char* data, int data_length)
72         {
73                 SI->Log(DEBUG,"AddData, %d bytes to add", data_length);
74                 if ((data_length + bufptr) > bufsz)
75                 {
76                         SI->Log(DEBUG,"Need to extend buffer to %d, is now %d", data_length + bufptr, bufsz);
77                         /* Buffer is too small, enlarge it and copy contents */
78                         int old_bufsz = bufsz;
79                         unsigned char* temp = buffer;
80
81                         bufsz += data_length;
82                         buffer = new unsigned char[bufsz + 1];
83
84                         memcpy(buffer, temp, old_bufsz);
85
86                         delete[] temp;
87                 }
88
89                 SI->Log(DEBUG,"Copy data in at pos %d", bufptr);
90
91                 memcpy(buffer + bufptr, data, data_length);
92                 bufptr += data_length;
93                 amount_read += data_length;
94
95                 SI->Log(DEBUG,"Amount read is now %d, bufptr is now %d", amount_read, bufptr);
96
97                 if ((!amount_expected) && (amount_read >= 4))
98                 {
99                         SI->Log(DEBUG,"We dont yet have an expected amount");
100                         /* We have enough to read an int */
101                         int* size = (int*)buffer;
102                         amount_expected = ntohl(*size);
103                         SI->Log(DEBUG,"Expected amount is %d", amount_expected);
104                 }
105         }
106
107         int GetFrame(unsigned char* frame, int maxsize)
108         {
109                 if (amount_expected)
110                 {
111                         SI->Log(DEBUG,"Were expecting a frame of size %d", amount_expected);
112                         /* We know how much we're expecting...
113                          * Do we have enough yet?
114                          */
115                         if ((amount_read - 4) >= amount_expected)
116                         {
117                                 SI->Log(DEBUG,"We have enough for the frame (have %d)", (amount_read - 4));
118                                 int amt_ex = amount_expected;
119                                 /* Yes, we have enough now */
120                                 memcpy(frame, buffer + 4, amount_expected > maxsize ? maxsize : amount_expected);
121                                 RemoveFirstFrame();
122                                 return (amt_ex > maxsize) ? maxsize : amt_ex;
123                         }
124                 }
125                 /* Not enough for a frame yet, COME AGAIN! */
126                 return 0;
127         }
128
129         void RemoveFirstFrame()
130         {
131                 SI->Log(DEBUG,"Removing first frame from buffer sized %d", amount_expected);
132                 unsigned char* temp = buffer;
133
134                 bufsz -= (amount_expected + 4);
135                 buffer = new unsigned char[bufsz + 1];
136
137                 SI->Log(DEBUG,"Shrunk buffer to %d", bufsz);
138
139                 memcpy(buffer, temp + amount_expected + 4, bufsz);
140
141                 amount_read -= (amount_expected + 4);
142                 SI->Log(DEBUG,"Amount read now %d", amount_read);
143
144                 if (amount_read >= 4)
145                 {
146                         /* We have enough to read an int */
147                         int* size = (int*)buffer;
148                         amount_expected = ntohl(*size);
149                 }
150                 else
151                         amount_expected = 0;
152
153                 SI->Log(DEBUG,"Amount expected now %d", amount_expected);
154
155                 bufptr = 0;
156
157                 delete[] temp;
158         }
159 };
160
161 /** Represents an ZIP user's extra data
162  */
163 class izip_session : public classbase
164 {
165  public:
166         z_stream c_stream; /* compression stream */
167         z_stream d_stream; /* decompress stream */
168         izip_status status;
169         int fd;
170         CountedBuffer* inbuf;
171 };
172
173 class ModuleZLib : public Module
174 {
175         izip_session sessions[MAX_DESCRIPTORS];
176         float total_out_compressed;
177         float total_in_compressed;
178         float total_out_uncompressed;
179         float total_in_uncompressed;
180         
181  public:
182         
183         ModuleZLib(InspIRCd* Me)
184                 : Module::Module(Me)
185         {
186                 ServerInstance->PublishInterface("InspSocketHook", this);
187
188                 total_out_compressed = total_in_compressed = 0;
189                 total_out_uncompressed = total_out_uncompressed = 0;
190
191                 SI = ServerInstance;
192         }
193
194         virtual ~ModuleZLib()
195         {
196         }
197
198         virtual Version GetVersion()
199         {
200                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
201         }
202
203         void Implements(char* List)
204         {
205                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
206                 List[I_OnStats] = List[I_OnRequest] = 1;
207         }
208
209         virtual char* OnRequest(Request* request)
210         {
211                 ISHRequest* ISR = (ISHRequest*)request;
212                 if (strcmp("IS_NAME", request->GetId()) == 0)
213                 {
214                         return "zip";
215                 }
216                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
217                 {
218                         char* ret = "OK";
219                         try
220                         {
221                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
222                         }
223                         catch (ModuleException& e)
224                         {
225                                 return NULL;
226                         }
227                         return ret;
228                 }
229                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
230                 {
231                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
232                 }
233                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
234                 {
235                         return "OK";
236                 }
237                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
238                 {
239                         return NULL;
240                 }
241                 return NULL;
242         }
243
244         virtual int OnStats(char symbol, userrec* user, string_list &results)
245         {
246                 if (symbol == 'z')
247                 {
248                         std::string sn = ServerInstance->Config->ServerName;
249
250                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
251                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
252
253                         float total_compressed = total_in_compressed + total_out_compressed;
254                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
255
256                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
257
258                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
259
260                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
261                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
262                         sprintf(combined_ratio, "%3.2f%%", total_r);
263
264                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
265                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
266                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
267                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
268                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
269                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
270                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
271                         return 0;
272                 }
273
274                 return 0;
275         }
276
277         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
278         {
279                 izip_session* session = &sessions[fd];
280         
281                 /* allocate deflate state */
282                 session->fd = fd;
283                 session->status = IZIP_OPEN;
284
285                 session->inbuf = new CountedBuffer();
286                 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
287
288                 session->c_stream.zalloc = (alloc_func)0;
289                 session->c_stream.zfree = (free_func)0;
290                 session->c_stream.opaque = (voidpf)0;
291
292                 session->d_stream.zalloc = (alloc_func)0;
293                 session->d_stream.zfree = (free_func)0;
294                 session->d_stream.opaque = (voidpf)0;
295         }
296
297         virtual void OnRawSocketConnect(int fd)
298         {
299                 OnRawSocketAccept(fd, "", 0);
300         }
301
302         virtual void OnRawSocketClose(int fd)
303         {
304                 CloseSession(&sessions[fd]);
305         }
306         
307         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
308         {
309                 izip_session* session = &sessions[fd];
310
311                 if (session->status == IZIP_CLOSED)
312                         return 1;
313
314                 unsigned char compr[CHUNK + 1];
315                 unsigned int total_decomp = 0;
316
317                 readresult = read(fd, compr, CHUNK);
318
319                 if (readresult > 0)
320                 {
321                         session->inbuf->AddData(compr, readresult);
322         
323                         int size = session->inbuf->GetFrame(compr, CHUNK);
324                         while ((size) && (total_decomp < count))
325                         {
326         
327                                 session->d_stream.next_in  = (Bytef*)compr;
328                                 session->d_stream.avail_in = 0;
329                                 session->d_stream.next_out = (Bytef*)(buffer + total_decomp);
330                                 if (inflateInit(&session->d_stream) != Z_OK)
331                                         return -EBADF;
332         
333                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
334                                 {
335                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
336                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
337                                                 break;
338                                 }
339         
340                                 inflateEnd(&session->d_stream);
341         
342                                 total_in_compressed += readresult;
343                                 readresult = session->d_stream.total_out;
344                                 total_in_uncompressed += session->d_stream.total_out;
345         
346                                 total_decomp += session->d_stream.total_out;
347
348                                 ServerInstance->Log(DEBUG,"Decompressed %d bytes, total_decomp=%d: '%s'", session->d_stream.total_out, total_decomp, buffer);
349
350                                 if (total_decomp < count)
351                                         size = session->inbuf->GetFrame(compr, CHUNK);
352                         }
353
354                         buffer[total_decomp] = 0;
355
356                         ServerInstance->Log(DEBUG,"Complete buffer: '%s' size=%d", buffer, total_decomp);
357                 }
358                 return (readresult > 0);
359         }
360
361         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
362         {
363                 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
364
365                 izip_session* session = &sessions[fd];
366                 int ocount = count;
367
368                 if (!count)
369                 {
370                         ServerInstance->Log(DEBUG,"Nothing to do!");
371                         return 1;
372                 }
373
374                 if(session->status != IZIP_OPEN)
375                 {
376                         CloseSession(session);
377                         return 0;
378                 }
379
380                 unsigned char compr[CHUNK];
381
382                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
383                 {
384                         ServerInstance->Log(DEBUG,"Deflate init failed");
385                 }
386
387                 session->c_stream.next_in  = (Bytef*)buffer;
388                 session->c_stream.next_out = compr+4;
389
390                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
391                 {
392                         session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
393                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
394                         {
395                                 ServerInstance->Log(DEBUG,"Couldnt deflate!");
396                                 CloseSession(session);
397                                 return 0;
398                         }
399                 }
400                 /* Finish the stream, still forcing small buffers: */
401                 for (;;)
402                 {
403                         session->c_stream.avail_out = 1;
404                         if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
405                                 break;
406                 }
407
408                 deflateEnd(&session->c_stream);
409
410                 total_out_uncompressed += ocount;
411                 total_out_compressed += session->c_stream.total_out;
412
413                 int x = htonl(session->c_stream.total_out);
414                 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
415                  * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
416                  * assembling the frame size into the same packet as the compressed frame.
417                  */
418                 memcpy(compr, &x, sizeof(x));
419                 write(fd, compr, session->c_stream.total_out+4);
420
421                 ServerInstance->Log(DEBUG,"Sending frame of size %d", x);
422
423                 return ocount;
424         }
425         
426         void CloseSession(izip_session* session)
427         {
428                 if (session->status = IZIP_OPEN)
429                 {
430                         session->status = IZIP_CLOSED;
431                         delete session->inbuf;
432                 }
433         }
434
435 };
436
437 class ModuleZLibFactory : public ModuleFactory
438 {
439  public:
440         ModuleZLibFactory()
441         {
442         }
443         
444         ~ModuleZLibFactory()
445         {
446         }
447         
448         virtual Module * CreateModule(InspIRCd* Me)
449         {
450                 return new ModuleZLib(Me);
451         }
452 };
453
454
455 extern "C" void * init_module( void )
456 {
457         return new ModuleZLibFactory;
458 }