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