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