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