]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
63c0862cdb8500801bdadcf6675074508ff0ca45
[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                         /* We have enough to read an int */
73                         char sz[4];
74                         for (int i = 0; i < 4; i++)
75                         {
76                                 sz[i] = buffer.front();
77                                 buffer.pop_front();
78                         }
79                         int* size = (int*)sz;
80                         amount_expected = ntohl(*size);
81                 }
82         }
83
84         int GetFrame(unsigned char* frame, int maxsize)
85         {
86                 if (amount_expected)
87                 {
88                         SI->Log(DEBUG,"Were expecting a frame of size %d", amount_expected);
89                         /* We know how much we're expecting...
90                          * Do we have enough yet?
91                          */
92                         if (buffer.size() >= amount_expected)
93                         {
94                                 int j = 0;
95                                 for (unsigned int i = 0; i < amount_expected; i++, j++)
96                                 {
97                                         frame[i] = buffer.front();
98                                         buffer.pop_front();
99                                 }
100
101                                 amount_expected = 0;
102                                 NextFrameSize();
103
104                                 return j;
105                         }
106                 }
107                 /* Not enough for a frame yet, COME AGAIN! */
108                 return 0;
109         }
110 };
111
112 /** Represents an ZIP user's extra data
113  */
114 class izip_session : public classbase
115 {
116  public:
117         z_stream c_stream; /* compression stream */
118         z_stream d_stream; /* decompress stream */
119         izip_status status;
120         int fd;
121         CountedBuffer* inbuf;
122 };
123
124 class ModuleZLib : public Module
125 {
126         izip_session sessions[MAX_DESCRIPTORS];
127         float total_out_compressed;
128         float total_in_compressed;
129         float total_out_uncompressed;
130         float total_in_uncompressed;
131         
132  public:
133         
134         ModuleZLib(InspIRCd* Me)
135                 : Module::Module(Me)
136         {
137                 ServerInstance->PublishInterface("InspSocketHook", this);
138
139                 total_out_compressed = total_in_compressed = 0;
140                 total_out_uncompressed = total_out_uncompressed = 0;
141
142                 SI = ServerInstance;
143         }
144
145         virtual ~ModuleZLib()
146         {
147         }
148
149         virtual Version GetVersion()
150         {
151                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
152         }
153
154         void Implements(char* List)
155         {
156                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
157                 List[I_OnStats] = List[I_OnRequest] = 1;
158         }
159
160         virtual char* OnRequest(Request* request)
161         {
162                 ISHRequest* ISR = (ISHRequest*)request;
163                 if (strcmp("IS_NAME", request->GetId()) == 0)
164                 {
165                         return "zip";
166                 }
167                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
168                 {
169                         char* ret = "OK";
170                         try
171                         {
172                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
173                         }
174                         catch (ModuleException& e)
175                         {
176                                 return NULL;
177                         }
178                         return ret;
179                 }
180                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
181                 {
182                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
183                 }
184                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
185                 {
186                         return "OK";
187                 }
188                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
189                 {
190                         return NULL;
191                 }
192                 return NULL;
193         }
194
195         virtual int OnStats(char symbol, userrec* user, string_list &results)
196         {
197                 if (symbol == 'z')
198                 {
199                         std::string sn = ServerInstance->Config->ServerName;
200
201                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
202                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
203
204                         float total_compressed = total_in_compressed + total_out_compressed;
205                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
206
207                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
208
209                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
210
211                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
212                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
213                         sprintf(combined_ratio, "%3.2f%%", total_r);
214
215                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
216                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
217                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
218                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
219                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
220                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
221                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
222                         return 0;
223                 }
224
225                 return 0;
226         }
227
228         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
229         {
230                 izip_session* session = &sessions[fd];
231         
232                 /* allocate deflate state */
233                 session->fd = fd;
234                 session->status = IZIP_OPEN;
235
236                 session->inbuf = new CountedBuffer();
237                 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
238
239                 session->c_stream.zalloc = (alloc_func)0;
240                 session->c_stream.zfree = (free_func)0;
241                 session->c_stream.opaque = (voidpf)0;
242
243                 session->d_stream.zalloc = (alloc_func)0;
244                 session->d_stream.zfree = (free_func)0;
245                 session->d_stream.opaque = (voidpf)0;
246         }
247
248         virtual void OnRawSocketConnect(int fd)
249         {
250                 OnRawSocketAccept(fd, "", 0);
251         }
252
253         virtual void OnRawSocketClose(int fd)
254         {
255                 CloseSession(&sessions[fd]);
256         }
257         
258         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
259         {
260                 izip_session* session = &sessions[fd];
261
262                 if (session->status == IZIP_CLOSED)
263                         return 1;
264
265                 unsigned char compr[CHUNK + 1];
266
267                 readresult = read(fd, compr, CHUNK);
268
269                 if (readresult > 0)
270                 {
271                         session->inbuf->AddData(compr, readresult);
272         
273                         int size = 0;
274                         std::string str_out;
275                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
276                         {
277                                 unsigned char localbuf[count + 1];
278                                 ServerInstance->Log(DEBUG,"Got size %d", size);
279
280                                 session->d_stream.next_in  = (Bytef*)compr;
281                                 session->d_stream.avail_in = 0;
282                                 session->d_stream.next_out = (Bytef*)localbuf;
283                                 if (inflateInit(&session->d_stream) != Z_OK)
284                                         return -EBADF;
285         
286                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
287                                 {
288                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
289                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
290                                                 break;
291                                 }
292         
293                                 inflateEnd(&session->d_stream);
294
295                                 ServerInstance->Log(DEBUG,"Decompressed size: %d", session->d_stream.total_out);
296
297                                 localbuf[session->d_stream.total_out] = 0;
298                                 str_out.append((const char*)localbuf);
299
300                                 ServerInstance->Log(DEBUG,"str_out size: %d", str_out.length());
301         
302                                 total_in_compressed += readresult;
303                                 readresult = session->d_stream.total_out;
304                                 total_in_uncompressed += session->d_stream.total_out;
305                         }
306
307                         memcpy(buffer, str_out.data(), str_out.length() > count ? count : str_out.length());
308
309                         ServerInstance->Log(DEBUG,"Complete buffer size=%d: '%s'\r\n\r\n", str_out.length(), buffer);
310
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                 write(fd, compr, session->c_stream.total_out+4);
375
376                 ServerInstance->Log(DEBUG,"Sending frame of size %d", ntohl(x));
377
378                 return ocount;
379         }
380         
381         void CloseSession(izip_session* session)
382         {
383                 if (session->status = IZIP_OPEN)
384                 {
385                         session->status = IZIP_CLOSED;
386                         delete session->inbuf;
387                 }
388         }
389
390 };
391
392 class ModuleZLibFactory : public ModuleFactory
393 {
394  public:
395         ModuleZLibFactory()
396         {
397         }
398         
399         ~ModuleZLibFactory()
400         {
401         }
402         
403         virtual Module * CreateModule(InspIRCd* Me)
404         {
405                 return new ModuleZLib(Me);
406         }
407 };
408
409
410 extern "C" void * init_module( void )
411 {
412         return new ModuleZLibFactory;
413 }