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