]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
79a4e5b08e0e1a2463d8d628145039ec4313d5bb
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <zlib.h>
16 #include "users.h"
17 #include "channels.h"
18 #include "modules.h"
19 #include "socket.h"
20 #include "hashcomp.h"
21 #include "transport.h"
22
23 /* $ModDesc: Provides zlib link support for servers */
24 /* $LinkerFlags: -lz */
25 /* $ModDep: transport.h */
26
27 /*
28  * Compressed data is transmitted across the link in the following format:
29  *
30  *   0   1   2   3   4 ... n
31  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
32  * |       n       |              Z0 -> Zn                         |
33  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
34  *
35  * Where: n is the size of a frame, in network byte order, 4 bytes.
36  * Z0 through Zn are Zlib compressed data, n bytes in length.
37  *
38  * If the module fails to read the entire frame, then it will buffer
39  * the portion of the last frame it received, then attempt to read
40  * the next part of the frame next time a write notification arrives.
41  *
42  * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
43  * a flush after each frame. A frame may contain multiple lines
44  * and should be treated as raw binary data.
45  *
46  */
47
48 /* Status of a connection */
49 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
50
51 /* Maximum transfer size per read operation */
52 const unsigned int CHUNK = 128 * 1024;
53
54 /* This class manages a compressed chunk of data preceeded by
55  * a length count.
56  *
57  * It can handle having multiple chunks of data in the buffer
58  * at any time.
59  */
60 class CountedBuffer : public classbase
61 {
62         std::string buffer;             /* Current buffer contents */
63         unsigned int amount_expected;   /* Amount of data expected */
64  public:
65         CountedBuffer()
66         {
67                 amount_expected = 0;
68         }
69
70         /** Adds arbitrary compressed data to the buffer.
71          * - Binsry safe, of course.
72          */
73         void AddData(unsigned char* data, int data_length)
74         {
75                 buffer.append((const char*)data, data_length);
76                 this->NextFrameSize();
77         }
78
79         /** Works out the size of the next compressed frame
80          */
81         void NextFrameSize()
82         {
83                 if ((!amount_expected) && (buffer.length() >= 4))
84                 {
85                         /* We have enough to read an int -
86                          * Yes, this is safe, but its ugly. Give me
87                          * a nicer way to read 4 bytes from a binary
88                          * stream, and push them into a 32 bit int,
89                          * and i'll consider replacing this.
90                          */
91                         amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
92                         buffer = buffer.substr(4);
93                 }
94         }
95
96         /** Gets the next frame and returns its size, or returns
97          * zero if there isnt one available yet.
98          * A frame can contain multiple plaintext lines.
99          * - Binary safe.
100          */
101         int GetFrame(unsigned char* frame, int maxsize)
102         {
103                 if (amount_expected)
104                 {
105                         /* We know how much we're expecting...
106                          * Do we have enough yet?
107                          */
108                         if (buffer.length() >= amount_expected)
109                         {
110                                 int j = 0;
111                                 for (unsigned int i = 0; i < amount_expected; i++, j++)
112                                         frame[i] = buffer[i];
113
114                                 buffer = buffer.substr(j);
115                                 amount_expected = 0;
116                                 NextFrameSize();
117                                 return j;
118                         }
119                 }
120                 /* Not enough for a frame yet, COME AGAIN! */
121                 return 0;
122         }
123 };
124
125 /** Represents an zipped connections extra data
126  */
127 class izip_session : public classbase
128 {
129  public:
130         z_stream c_stream;      /* compression stream */
131         z_stream d_stream;      /* decompress stream */
132         izip_status status;     /* Connection status */
133         int fd;                 /* File descriptor */
134         CountedBuffer* inbuf;   /* Holds input buffer */
135         std::string outbuf;     /* Holds output buffer */
136 };
137
138 class ModuleZLib : public Module
139 {
140         izip_session sessions[MAX_DESCRIPTORS];
141
142         /* Used for stats z extensions */
143         float total_out_compressed;
144         float total_in_compressed;
145         float total_out_uncompressed;
146         float total_in_uncompressed;
147         
148  public:
149         
150         ModuleZLib(InspIRCd* Me)
151                 : Module::Module(Me)
152         {
153                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
154
155                 total_out_compressed = total_in_compressed = 0;
156                 total_out_uncompressed = total_out_uncompressed = 0;
157                 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnStats, I_OnRequest };
158                 ServerInstance->Modules->Attach(eventlist, this, 7);
159         }
160
161         virtual ~ModuleZLib()
162         {
163                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
164         }
165
166         virtual Version GetVersion()
167         {
168                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
169         }
170
171
172         /* Handle BufferedSocketHook API requests */
173         virtual char* OnRequest(Request* request)
174         {
175                 ISHRequest* ISR = (ISHRequest*)request;
176                 if (strcmp("IS_NAME", request->GetId()) == 0)
177                 {
178                         /* Return name */
179                         return "zip";
180                 }
181                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
182                 {
183                         /* Attach to an inspsocket */
184                         char* ret = "OK";
185                         try
186                         {
187                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
188                         }
189                         catch (ModuleException& e)
190                         {
191                                 return NULL;
192                         }
193                         return ret;
194                 }
195                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
196                 {
197                         /* Detatch from an inspsocket */
198                         return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
199                 }
200                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
201                 {
202                         /* Check for completion of handshake
203                          * (actually, this module doesnt handshake)
204                          */
205                         return "OK";
206                 }
207                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
208                 {
209                         /* Attach certificate data to the inspsocket
210                          * (this module doesnt do that, either)
211                          */
212                         return NULL;
213                 }
214                 return NULL;
215         }
216
217         /* Handle stats z (misc stats) */
218         virtual int OnStats(char symbol, User* user, string_list &results)
219         {
220                 if (symbol == 'z')
221                 {
222                         std::string sn = ServerInstance->Config->ServerName;
223
224                         /* Yeah yeah, i know, floats are ew.
225                          * We used them here because we'd be casting to float anyway to do this maths,
226                          * and also only floating point numbers can deal with the pretty large numbers
227                          * involved in the total throughput of a server over a large period of time.
228                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
229                          * can still hold more.
230                          */
231                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
232                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
233
234                         float total_compressed = total_in_compressed + total_out_compressed;
235                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
236
237                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
238
239                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
240
241                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
242                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
243                         sprintf(combined_ratio, "%3.2f%%", total_r);
244
245                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
246                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
247                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
248                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
249                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
250                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
251                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
252                         return 0;
253                 }
254
255                 return 0;
256         }
257
258         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
259         {
260                 izip_session* session = &sessions[fd];
261         
262                 /* allocate state and buffers */
263                 session->fd = fd;
264                 session->status = IZIP_OPEN;
265                 session->inbuf = new CountedBuffer();
266
267                 session->c_stream.zalloc = (alloc_func)0;
268                 session->c_stream.zfree = (free_func)0;
269                 session->c_stream.opaque = (voidpf)0;
270
271                 session->d_stream.zalloc = (alloc_func)0;
272                 session->d_stream.zfree = (free_func)0;
273                 session->d_stream.opaque = (voidpf)0;
274         }
275
276         virtual void OnRawSocketConnect(int fd)
277         {
278                 /* Nothing special needs doing here compared to accept() */
279                 OnRawSocketAccept(fd, "", 0);
280         }
281
282         virtual void OnRawSocketClose(int fd)
283         {
284                 CloseSession(&sessions[fd]);
285         }
286
287         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
288         {
289                 /* Find the sockets session */
290                 izip_session* session = &sessions[fd];
291
292                 if (session->status == IZIP_CLOSED)
293                         return 0;
294
295                 unsigned char compr[CHUNK + 4];
296                 unsigned int offset = 0;
297                 unsigned int total_size = 0;
298
299                 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
300                 readresult = read(fd, compr, CHUNK);
301
302                 /* Did we get anything? */
303                 if (readresult > 0)
304                 {
305                         /* Add it to the frame queue */
306                         session->inbuf->AddData(compr, readresult);
307                         total_in_compressed += readresult;
308         
309                         /* Parse all completed frames */
310                         int size = 0;
311                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
312                         {
313                                 session->d_stream.next_in  = (Bytef*)compr;
314                                 session->d_stream.avail_in = 0;
315                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
316
317                                 /* If we cant call this, well, we're boned. */
318                                 if (inflateInit(&session->d_stream) != Z_OK)
319                                         return 0;
320         
321                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
322                                 {
323                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
324                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
325                                                 break;
326                                 }
327         
328                                 /* Stick a fork in me, i'm done */
329                                 inflateEnd(&session->d_stream);
330
331                                 /* Update counters and offsets */
332                                 total_size += session->d_stream.total_out;
333                                 total_in_uncompressed += session->d_stream.total_out;
334                                 offset += session->d_stream.total_out;
335                         }
336
337                         /* Null-terminate the buffer -- this doesnt harm binary data */
338                         buffer[total_size] = 0;
339
340                         /* Set the read size to the correct total size */
341                         readresult = total_size;
342
343                 }
344                 return (readresult > 0);
345         }
346
347         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
348         {
349                 izip_session* session = &sessions[fd];
350                 int ocount = count;
351
352                 if (!count)     /* Nothing to do! */
353                         return 0;
354
355                 if(session->status != IZIP_OPEN)
356                 {
357                         /* Seriously, wtf? */
358                         CloseSession(session);
359                         return 0;
360                 }
361
362                 unsigned char compr[CHUNK + 4];
363
364                 /* Gentlemen, start your engines! */
365                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
366                 {
367                         CloseSession(session);
368                         return 0;
369                 }
370
371                 /* Set buffer sizes (we reserve 4 bytes at the start of the
372                  * buffer for the length counters)
373                  */
374                 session->c_stream.next_in  = (Bytef*)buffer;
375                 session->c_stream.next_out = compr + 4;
376
377                 /* Compress the text */
378                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
379                 {
380                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
381                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
382                         {
383                                 CloseSession(session);
384                                 return 0;
385                         }
386                 }
387                 /* Finish the stream */
388                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
389                 deflateEnd(&session->c_stream);
390
391                 total_out_uncompressed += ocount;
392                 total_out_compressed += session->c_stream.total_out;
393
394                 /** Assemble the frame length onto the frame, in network byte order */
395                 compr[0] = (session->c_stream.total_out >> 24);
396                 compr[1] = (session->c_stream.total_out >> 16);
397                 compr[2] = (session->c_stream.total_out >> 8);
398                 compr[3] = (session->c_stream.total_out & 0xFF);
399
400                 /* Add compressed data plus leading length to the output buffer -
401                  * Note, we may have incomplete half-sent frames in here.
402                  */
403                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
404
405                 /* Lets see how much we can send out */
406                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
407
408                 /* Check for errors, and advance the buffer if any was sent */
409                 if (ret > 0)
410                         session->outbuf = session->outbuf.substr(ret);
411                 else if (ret < 1)
412                 {
413                         if (ret == -1)
414                         {
415                                 if (errno == EAGAIN)
416                                         return 0;
417                                 else
418                                 {
419                                         session->outbuf.clear();
420                                         return 0;
421                                 }
422                         }
423                         else
424                         {
425                                 session->outbuf.clear();
426                                 return 0;
427                         }
428                 }
429
430                 /* ALL LIES the lot of it, we havent really written
431                  * this amount, but the layer above doesnt need to know.
432                  */
433                 return ocount;
434         }
435         
436         void CloseSession(izip_session* session)
437         {
438                 if (session->status == IZIP_OPEN)
439                 {
440                         session->status = IZIP_CLOSED;
441                         session->outbuf.clear();
442                         delete session->inbuf;
443                 }
444         }
445
446 };
447
448 MODULE_INIT(ModuleZLib)
449