1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
19 #include "inspircd_config.h"
20 #include "configreader.h"
29 #include "transport.h"
31 /* $ModDesc: Provides zlib link support for servers */
32 /* $LinkerFlags: -lz */
33 /* $ModDep: transport.h */
36 * Compressed data is transmitted across the link in the following format:
39 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
41 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
43 * Where: n is the size of a frame, in network byte order, 4 bytes.
44 * Z0 through Zn are Zlib compressed data, n bytes in length.
46 * If the module fails to read the entire frame, then it will buffer
47 * the portion of the last frame it received, then attempt to read
48 * the next part of the frame next time a write notification arrives.
50 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
51 * a flush after each frame. A frame may contain multiple lines
52 * and should be treated as raw binary data.
56 /* Status of a connection */
57 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
59 /* Maximum transfer size per read operation */
60 const unsigned int CHUNK = 128 * 1024;
62 /* This class manages a compressed chunk of data preceeded by
65 * It can handle having multiple chunks of data in the buffer
68 class CountedBuffer : public classbase
70 std::string buffer; /* Current buffer contents */
71 unsigned int amount_expected; /* Amount of data expected */
78 /** Adds arbitrary compressed data to the buffer.
79 * - Binsry safe, of course.
81 void AddData(unsigned char* data, int data_length)
83 buffer.append((const char*)data, data_length);
84 this->NextFrameSize();
87 /** Works out the size of the next compressed frame
91 if ((!amount_expected) && (buffer.length() >= 4))
93 /* We have enough to read an int -
94 * Yes, this is safe, but its ugly. Give me
95 * a nicer way to read 4 bytes from a binary
96 * stream, and push them into a 32 bit int,
97 * and i'll consider replacing this.
99 amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
100 buffer = buffer.substr(4);
104 /** Gets the next frame and returns its size, or returns
105 * zero if there isnt one available yet.
106 * A frame can contain multiple plaintext lines.
109 int GetFrame(unsigned char* frame, int maxsize)
113 /* We know how much we're expecting...
114 * Do we have enough yet?
116 if (buffer.length() >= amount_expected)
119 for (unsigned int i = 0; i < amount_expected; i++, j++)
120 frame[i] = buffer[i];
122 buffer = buffer.substr(j);
128 /* Not enough for a frame yet, COME AGAIN! */
133 /** Represents an zipped connections extra data
135 class izip_session : public classbase
138 z_stream c_stream; /* compression stream */
139 z_stream d_stream; /* decompress stream */
140 izip_status status; /* Connection status */
141 int fd; /* File descriptor */
142 CountedBuffer* inbuf; /* Holds input buffer */
143 std::string outbuf; /* Holds output buffer */
146 class ModuleZLib : public Module
148 izip_session sessions[MAX_DESCRIPTORS];
150 /* Used for stats z extensions */
151 float total_out_compressed;
152 float total_in_compressed;
153 float total_out_uncompressed;
154 float total_in_uncompressed;
158 ModuleZLib(InspIRCd* Me)
161 ServerInstance->PublishInterface("InspSocketHook", this);
163 total_out_compressed = total_in_compressed = 0;
164 total_out_uncompressed = total_out_uncompressed = 0;
167 virtual ~ModuleZLib()
169 ServerInstance->UnpublishInterface("InspSocketHook", this);
172 virtual Version GetVersion()
174 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
177 void Implements(char* List)
179 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
180 List[I_OnStats] = List[I_OnRequest] = 1;
183 /* Handle InspSocketHook API requests */
184 virtual char* OnRequest(Request* request)
186 ISHRequest* ISR = (ISHRequest*)request;
187 if (strcmp("IS_NAME", request->GetId()) == 0)
192 else if (strcmp("IS_HOOK", request->GetId()) == 0)
194 /* Attach to an inspsocket */
198 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
200 catch (ModuleException& e)
206 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
208 /* Detatch from an inspsocket */
209 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
211 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
213 /* Check for completion of handshake
214 * (actually, this module doesnt handshake)
218 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
220 /* Attach certificate data to the inspsocket
221 * (this module doesnt do that, either)
228 /* Handle stats z (misc stats) */
229 virtual int OnStats(char symbol, userrec* user, string_list &results)
233 std::string sn = ServerInstance->Config->ServerName;
235 /* Yeah yeah, i know, floats are ew.
236 * We used them here because we'd be casting to float anyway to do this maths,
237 * and also only floating point numbers can deal with the pretty large numbers
238 * involved in the total throughput of a server over a large period of time.
239 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
240 * can still hold more.
242 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
243 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
245 float total_compressed = total_in_compressed + total_out_compressed;
246 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
248 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
250 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
252 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
253 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
254 sprintf(combined_ratio, "%3.2f%%", total_r);
256 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
257 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
258 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
259 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
260 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
261 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
262 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
269 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
271 izip_session* session = &sessions[fd];
273 /* allocate state and buffers */
275 session->status = IZIP_OPEN;
276 session->inbuf = new CountedBuffer();
278 session->c_stream.zalloc = (alloc_func)0;
279 session->c_stream.zfree = (free_func)0;
280 session->c_stream.opaque = (voidpf)0;
282 session->d_stream.zalloc = (alloc_func)0;
283 session->d_stream.zfree = (free_func)0;
284 session->d_stream.opaque = (voidpf)0;
287 virtual void OnRawSocketConnect(int fd)
289 /* Nothing special needs doing here compared to accept() */
290 OnRawSocketAccept(fd, "", 0);
293 virtual void OnRawSocketClose(int fd)
295 CloseSession(&sessions[fd]);
298 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
300 /* Find the sockets session */
301 izip_session* session = &sessions[fd];
303 if (session->status == IZIP_CLOSED)
306 unsigned char compr[CHUNK + 4];
307 unsigned int offset = 0;
308 unsigned int total_size = 0;
310 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
311 readresult = read(fd, compr, CHUNK);
313 /* Did we get anything? */
316 /* Add it to the frame queue */
317 session->inbuf->AddData(compr, readresult);
318 total_in_compressed += readresult;
320 /* Parse all completed frames */
322 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
324 session->d_stream.next_in = (Bytef*)compr;
325 session->d_stream.avail_in = 0;
326 session->d_stream.next_out = (Bytef*)(buffer + offset);
328 /* If we cant call this, well, we're boned. */
329 if (inflateInit(&session->d_stream) != Z_OK)
332 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
334 session->d_stream.avail_in = session->d_stream.avail_out = 1;
335 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
339 /* Stick a fork in me, i'm done */
340 inflateEnd(&session->d_stream);
342 /* Update counters and offsets */
343 total_size += session->d_stream.total_out;
344 total_in_uncompressed += session->d_stream.total_out;
345 offset += session->d_stream.total_out;
348 /* Null-terminate the buffer -- this doesnt harm binary data */
349 buffer[total_size] = 0;
351 /* Set the read size to the correct total size */
352 readresult = total_size;
355 return (readresult > 0);
358 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
360 izip_session* session = &sessions[fd];
363 if (!count) /* Nothing to do! */
366 if(session->status != IZIP_OPEN)
368 /* Seriously, wtf? */
369 CloseSession(session);
373 unsigned char compr[CHUNK + 4];
375 /* Gentlemen, start your engines! */
376 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
378 CloseSession(session);
382 /* Set buffer sizes (we reserve 4 bytes at the start of the
383 * buffer for the length counters)
385 session->c_stream.next_in = (Bytef*)buffer;
386 session->c_stream.next_out = compr + 4;
388 /* Compress the text */
389 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
391 session->c_stream.avail_in = session->c_stream.avail_out = 1;
392 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
394 CloseSession(session);
398 /* Finish the stream */
399 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
400 deflateEnd(&session->c_stream);
402 total_out_uncompressed += ocount;
403 total_out_compressed += session->c_stream.total_out;
405 /** Assemble the frame length onto the frame, in network byte order */
406 compr[0] = (session->c_stream.total_out >> 24);
407 compr[1] = (session->c_stream.total_out >> 16);
408 compr[2] = (session->c_stream.total_out >> 8);
409 compr[3] = (session->c_stream.total_out & 0xFF);
411 /* Add compressed data plus leading length to the output buffer -
412 * Note, we may have incomplete half-sent frames in here.
414 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
416 /* Lets see how much we can send out */
417 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
419 /* Check for errors, and advance the buffer if any was sent */
421 session->outbuf = session->outbuf.substr(ret);
430 session->outbuf = "";
436 session->outbuf = "";
441 /* ALL LIES the lot of it, we havent really written
442 * this amount, but the layer above doesnt need to know.
447 void CloseSession(izip_session* session)
449 if (session->status = IZIP_OPEN)
451 session->status = IZIP_CLOSED;
452 session->outbuf = "";
453 delete session->inbuf;
459 class ModuleZLibFactory : public ModuleFactory
470 virtual Module * CreateModule(InspIRCd* Me)
472 return new ModuleZLib(Me);
477 extern "C" void * init_module( void )
479 return new ModuleZLibFactory;