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