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