]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
fce65d97e45757033090899acea886f984120d82
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 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         void Implements(char* List)
172         {
173                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
174                 List[I_OnStats] = List[I_OnRequest] = 1;
175         }
176
177         /* Handle BufferedSocketHook API requests */
178         virtual char* OnRequest(Request* request)
179         {
180                 ISHRequest* ISR = (ISHRequest*)request;
181                 if (strcmp("IS_NAME", request->GetId()) == 0)
182                 {
183                         /* Return name */
184                         return "zip";
185                 }
186                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
187                 {
188                         /* Attach to an inspsocket */
189                         char* ret = "OK";
190                         try
191                         {
192                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
193                         }
194                         catch (ModuleException& e)
195                         {
196                                 return NULL;
197                         }
198                         return ret;
199                 }
200                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
201                 {
202                         /* Detatch from an inspsocket */
203                         return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
204                 }
205                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
206                 {
207                         /* Check for completion of handshake
208                          * (actually, this module doesnt handshake)
209                          */
210                         return "OK";
211                 }
212                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
213                 {
214                         /* Attach certificate data to the inspsocket
215                          * (this module doesnt do that, either)
216                          */
217                         return NULL;
218                 }
219                 return NULL;
220         }
221
222         /* Handle stats z (misc stats) */
223         virtual int OnStats(char symbol, User* user, string_list &results)
224         {
225                 if (symbol == 'z')
226                 {
227                         std::string sn = ServerInstance->Config->ServerName;
228
229                         /* Yeah yeah, i know, floats are ew.
230                          * We used them here because we'd be casting to float anyway to do this maths,
231                          * and also only floating point numbers can deal with the pretty large numbers
232                          * involved in the total throughput of a server over a large period of time.
233                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
234                          * can still hold more.
235                          */
236                         float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
237                         float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
238
239                         float total_compressed = total_in_compressed + total_out_compressed;
240                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
241
242                         float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
243
244                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
245
246                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
247                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
248                         sprintf(combined_ratio, "%3.2f%%", total_r);
249
250                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
251                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
252                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
253                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
254                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);
255                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);
256                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);
257                         return 0;
258                 }
259
260                 return 0;
261         }
262
263         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
264         {
265                 izip_session* session = &sessions[fd];
266         
267                 /* allocate state and buffers */
268                 session->fd = fd;
269                 session->status = IZIP_OPEN;
270                 session->inbuf = new CountedBuffer();
271
272                 session->c_stream.zalloc = (alloc_func)0;
273                 session->c_stream.zfree = (free_func)0;
274                 session->c_stream.opaque = (voidpf)0;
275
276                 session->d_stream.zalloc = (alloc_func)0;
277                 session->d_stream.zfree = (free_func)0;
278                 session->d_stream.opaque = (voidpf)0;
279         }
280
281         virtual void OnRawSocketConnect(int fd)
282         {
283                 /* Nothing special needs doing here compared to accept() */
284                 OnRawSocketAccept(fd, "", 0);
285         }
286
287         virtual void OnRawSocketClose(int fd)
288         {
289                 CloseSession(&sessions[fd]);
290         }
291
292         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
293         {
294                 /* Find the sockets session */
295                 izip_session* session = &sessions[fd];
296
297                 if (session->status == IZIP_CLOSED)
298                         return 0;
299
300                 unsigned char compr[CHUNK + 4];
301                 unsigned int offset = 0;
302                 unsigned int total_size = 0;
303
304                 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
305                 readresult = read(fd, compr, CHUNK);
306
307                 /* Did we get anything? */
308                 if (readresult > 0)
309                 {
310                         /* Add it to the frame queue */
311                         session->inbuf->AddData(compr, readresult);
312                         total_in_compressed += readresult;
313         
314                         /* Parse all completed frames */
315                         int size = 0;
316                         while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
317                         {
318                                 session->d_stream.next_in  = (Bytef*)compr;
319                                 session->d_stream.avail_in = 0;
320                                 session->d_stream.next_out = (Bytef*)(buffer + offset);
321
322                                 /* If we cant call this, well, we're boned. */
323                                 if (inflateInit(&session->d_stream) != Z_OK)
324                                         return 0;
325         
326                                 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
327                                 {
328                                         session->d_stream.avail_in = session->d_stream.avail_out = 1;
329                                         if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
330                                                 break;
331                                 }
332         
333                                 /* Stick a fork in me, i'm done */
334                                 inflateEnd(&session->d_stream);
335
336                                 /* Update counters and offsets */
337                                 total_size += session->d_stream.total_out;
338                                 total_in_uncompressed += session->d_stream.total_out;
339                                 offset += session->d_stream.total_out;
340                         }
341
342                         /* Null-terminate the buffer -- this doesnt harm binary data */
343                         buffer[total_size] = 0;
344
345                         /* Set the read size to the correct total size */
346                         readresult = total_size;
347
348                 }
349                 return (readresult > 0);
350         }
351
352         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
353         {
354                 izip_session* session = &sessions[fd];
355                 int ocount = count;
356
357                 if (!count)     /* Nothing to do! */
358                         return 0;
359
360                 if(session->status != IZIP_OPEN)
361                 {
362                         /* Seriously, wtf? */
363                         CloseSession(session);
364                         return 0;
365                 }
366
367                 unsigned char compr[CHUNK + 4];
368
369                 /* Gentlemen, start your engines! */
370                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
371                 {
372                         CloseSession(session);
373                         return 0;
374                 }
375
376                 /* Set buffer sizes (we reserve 4 bytes at the start of the
377                  * buffer for the length counters)
378                  */
379                 session->c_stream.next_in  = (Bytef*)buffer;
380                 session->c_stream.next_out = compr + 4;
381
382                 /* Compress the text */
383                 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
384                 {
385                         session->c_stream.avail_in = session->c_stream.avail_out = 1;
386                         if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
387                         {
388                                 CloseSession(session);
389                                 return 0;
390                         }
391                 }
392                 /* Finish the stream */
393                 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
394                 deflateEnd(&session->c_stream);
395
396                 total_out_uncompressed += ocount;
397                 total_out_compressed += session->c_stream.total_out;
398
399                 /** Assemble the frame length onto the frame, in network byte order */
400                 compr[0] = (session->c_stream.total_out >> 24);
401                 compr[1] = (session->c_stream.total_out >> 16);
402                 compr[2] = (session->c_stream.total_out >> 8);
403                 compr[3] = (session->c_stream.total_out & 0xFF);
404
405                 /* Add compressed data plus leading length to the output buffer -
406                  * Note, we may have incomplete half-sent frames in here.
407                  */
408                 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
409
410                 /* Lets see how much we can send out */
411                 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
412
413                 /* Check for errors, and advance the buffer if any was sent */
414                 if (ret > 0)
415                         session->outbuf = session->outbuf.substr(ret);
416                 else if (ret < 1)
417                 {
418                         if (ret == -1)
419                         {
420                                 if (errno == EAGAIN)
421                                         return 0;
422                                 else
423                                 {
424                                         session->outbuf.clear();
425                                         return 0;
426                                 }
427                         }
428                         else
429                         {
430                                 session->outbuf.clear();
431                                 return 0;
432                         }
433                 }
434
435                 /* ALL LIES the lot of it, we havent really written
436                  * this amount, but the layer above doesnt need to know.
437                  */
438                 return ocount;
439         }
440         
441         void CloseSession(izip_session* session)
442         {
443                 if (session->status == IZIP_OPEN)
444                 {
445                         session->status = IZIP_CLOSED;
446                         session->outbuf.clear();
447                         delete session->inbuf;
448                 }
449         }
450
451 };
452
453 MODULE_INIT(ModuleZLib)
454