]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
355b086958a20a232d49bb01c4e4010ff5f13743
[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 = 16384;
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", session->d_stream.total_out);
349
350                                 size = session->inbuf->GetFrame(compr, CHUNK);
351                         }
352
353                         buffer[total_decomp] = 0;
354                 }
355                 return (readresult > 0);
356         }
357
358         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
359         {
360                 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
361
362                 izip_session* session = &sessions[fd];
363                 int ocount = count;
364
365                 if (!count)
366                 {
367                         ServerInstance->Log(DEBUG,"Nothing to do!");
368                         return 1;
369                 }
370
371                 if(session->status != IZIP_OPEN)
372                 {
373                         CloseSession(session);
374                         return 0;
375                 }
376
377                 unsigned char compr[count*2+4];
378
379                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
380                 {
381                         ServerInstance->Log(DEBUG,"Deflate init failed");
382                 }
383
384                 session->c_stream.next_in  = (Bytef*)buffer;
385                 session->c_stream.next_out = compr+4;
386
387                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < (unsigned int)count*2))
388                 {
389                         session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
390                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
391                         {
392                                 ServerInstance->Log(DEBUG,"Couldnt deflate!");
393                                 CloseSession(session);
394                                 return 0;
395                         }
396                 }
397                 /* Finish the stream, still forcing small buffers: */
398                 for (;;)
399                 {
400                         session->c_stream.avail_out = 1;
401                         if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
402                                 break;
403                 }
404
405                 deflateEnd(&session->c_stream);
406
407                 total_out_uncompressed += ocount;
408                 total_out_compressed += session->c_stream.total_out;
409
410                 int x = htonl(session->c_stream.total_out);
411                 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
412                  * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
413                  * assembling the frame size into the same packet as the compressed frame.
414                  */
415                 memcpy(compr, &x, sizeof(x));
416                 write(fd, compr, session->c_stream.total_out+4);
417
418                 return ocount;
419         }
420         
421         void CloseSession(izip_session* session)
422         {
423                 if (session->status = IZIP_OPEN)
424                 {
425                         session->status = IZIP_CLOSED;
426                         delete session->inbuf;
427                 }
428         }
429
430 };
431
432 class ModuleZLibFactory : public ModuleFactory
433 {
434  public:
435         ModuleZLibFactory()
436         {
437         }
438         
439         ~ModuleZLibFactory()
440         {
441         }
442         
443         virtual Module * CreateModule(InspIRCd* Me)
444         {
445                 return new ModuleZLib(Me);
446         }
447 };
448
449
450 extern "C" void * init_module( void )
451 {
452         return new ModuleZLibFactory;
453 }