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