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