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 * ---------------------------------------------------
22 #include "inspircd_config.h"
23 #include "configreader.h"
32 #include "transport.h"
34 /* $ModDesc: Provides zlib link support for servers */
35 /* $LinkerFlags: -lz */
36 /* $ModDep: transport.h */
39 * Compressed data is transmitted across the link in the following format:
42 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
44 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
46 * Where: n is the size of a frame, in network byte order, 4 bytes.
47 * Z0 through Zn are Zlib compressed data, n bytes in length.
49 * If the module fails to read the entire frame, then it will buffer
50 * the portion of the last frame it received, then attempt to read
51 * the next part of the frame next time a write notification arrives.
53 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
54 * a flush after each frame. A frame may contain multiple lines
55 * and should be treated as raw binary data.
59 /* Status of a connection */
60 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
62 /* Maximum transfer size per read operation */
63 const unsigned int CHUNK = 128 * 1024;
65 /* This class manages a compressed chunk of data preceeded by
68 * It can handle having multiple chunks of data in the buffer
71 class CountedBuffer : public classbase
73 std::string buffer; /* Current buffer contents */
74 unsigned int amount_expected; /* Amount of data expected */
81 /** Adds arbitrary compressed data to the buffer.
82 * - Binsry safe, of course.
84 void AddData(unsigned char* data, int data_length)
86 buffer.append((const char*)data, data_length);
87 this->NextFrameSize();
90 /** Works out the size of the next compressed frame
94 if ((!amount_expected) && (buffer.length() >= 4))
96 /* We have enough to read an int -
97 * Yes, this is safe, but its ugly. Give me
98 * a nicer way to read 4 bytes from a binary
99 * stream, and push them into a 32 bit int,
100 * and i'll consider replacing this.
102 amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
103 buffer = buffer.substr(4);
107 /** Gets the next frame and returns its size, or returns
108 * zero if there isnt one available yet.
109 * A frame can contain multiple plaintext lines.
112 int GetFrame(unsigned char* frame, int maxsize)
116 /* We know how much we're expecting...
117 * Do we have enough yet?
119 if (buffer.length() >= amount_expected)
122 for (unsigned int i = 0; i < amount_expected; i++, j++)
123 frame[i] = buffer[i];
125 buffer = buffer.substr(j);
131 /* Not enough for a frame yet, COME AGAIN! */
136 /** Represents an zipped connections extra data
138 class izip_session : public classbase
141 z_stream c_stream; /* compression stream */
142 z_stream d_stream; /* decompress stream */
143 izip_status status; /* Connection status */
144 int fd; /* File descriptor */
145 CountedBuffer* inbuf; /* Holds input buffer */
146 std::string outbuf; /* Holds output buffer */
149 class ModuleZLib : public Module
151 izip_session sessions[MAX_DESCRIPTORS];
153 /* Used for stats z extensions */
154 float total_out_compressed;
155 float total_in_compressed;
156 float total_out_uncompressed;
157 float total_in_uncompressed;
161 ModuleZLib(InspIRCd* Me)
164 ServerInstance->PublishInterface("InspSocketHook", this);
166 total_out_compressed = total_in_compressed = 0;
167 total_out_uncompressed = total_out_uncompressed = 0;
170 virtual ~ModuleZLib()
174 virtual Version GetVersion()
176 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
179 void Implements(char* List)
181 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
182 List[I_OnStats] = List[I_OnRequest] = 1;
185 /* Handle InspSocketHook API requests */
186 virtual char* OnRequest(Request* request)
188 ISHRequest* ISR = (ISHRequest*)request;
189 if (strcmp("IS_NAME", request->GetId()) == 0)
194 else if (strcmp("IS_HOOK", request->GetId()) == 0)
196 /* Attach to an inspsocket */
200 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
202 catch (ModuleException& e)
208 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
210 /* Detatch from an inspsocket */
211 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
213 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
215 /* Check for completion of handshake
216 * (actually, this module doesnt handshake)
220 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
222 /* Attach certificate data to the inspsocket
223 * (this module doesnt do that, either)
230 /* Handle stats z (misc stats) */
231 virtual int OnStats(char symbol, userrec* user, string_list &results)
235 std::string sn = ServerInstance->Config->ServerName;
237 /* Yeah yeah, i know, floats are ew.
238 * We used them here because we'd be casting to float anyway to do this maths,
239 * and also only floating point numbers can deal with the pretty large numbers
240 * involved in the total throughput of a server over a large period of time.
241 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
242 * can still hold more.
244 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
245 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
247 float total_compressed = total_in_compressed + total_out_compressed;
248 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
250 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
252 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
254 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
255 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
256 sprintf(combined_ratio, "%3.2f%%", total_r);
258 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
259 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
260 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
261 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
262 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
263 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
264 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
271 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
273 izip_session* session = &sessions[fd];
275 /* allocate state and buffers */
277 session->status = IZIP_OPEN;
278 session->inbuf = new CountedBuffer();
280 session->c_stream.zalloc = (alloc_func)0;
281 session->c_stream.zfree = (free_func)0;
282 session->c_stream.opaque = (voidpf)0;
284 session->d_stream.zalloc = (alloc_func)0;
285 session->d_stream.zfree = (free_func)0;
286 session->d_stream.opaque = (voidpf)0;
289 virtual void OnRawSocketConnect(int fd)
291 /* Nothing special needs doing here compared to accept() */
292 OnRawSocketAccept(fd, "", 0);
295 virtual void OnRawSocketClose(int fd)
297 CloseSession(&sessions[fd]);
300 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
302 /* Find the sockets session */
303 izip_session* session = &sessions[fd];
305 if (session->status == IZIP_CLOSED)
308 unsigned char compr[CHUNK + 4];
309 unsigned int offset = 0;
310 unsigned int total_size = 0;
312 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
313 readresult = read(fd, compr, CHUNK);
315 /* Did we get anything? */
318 /* Add it to the frame queue */
319 session->inbuf->AddData(compr, readresult);
321 /* Parse all completed frames */
323 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
325 session->d_stream.next_in = (Bytef*)compr;
326 session->d_stream.avail_in = 0;
327 session->d_stream.next_out = (Bytef*)(buffer + offset);
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 inflateEnd(&session->d_stream);
341 total_in_compressed += readresult;
342 total_size += session->d_stream.total_out;
343 total_in_uncompressed += session->d_stream.total_out;
344 offset += session->d_stream.total_out;
347 buffer[total_size] = 0;
348 readresult = total_size;
351 return (readresult > 0);
354 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
356 izip_session* session = &sessions[fd];
359 if (!count) /* Nothing to do! */
362 if(session->status != IZIP_OPEN)
364 /* Seriously, wtf? */
365 CloseSession(session);
369 unsigned char compr[CHUNK + 4];
371 /* Gentlemen, start your engines! */
372 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
374 CloseSession(session);
378 /* Set buffer sizes (we reserve 4 bytes at the start of the
379 * buffer for the length counters)
381 session->c_stream.next_in = (Bytef*)buffer;
382 session->c_stream.next_out = compr + 4;
384 /* Compress the text */
385 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
387 session->c_stream.avail_in = session->c_stream.avail_out = 1;
388 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
390 CloseSession(session);
394 /* Finish the stream */
395 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
396 deflateEnd(&session->c_stream);
398 total_out_uncompressed += ocount;
399 total_out_compressed += session->c_stream.total_out;
401 /** Assemble the frame length onto the frame, in network byte order */
402 compr[0] = (session->c_stream.total_out >> 24);
403 compr[1] = (session->c_stream.total_out >> 16);
404 compr[2] = (session->c_stream.total_out >> 8);
405 compr[3] = (session->c_stream.total_out & 0xFF);
407 /* Add compressed data plus leading length to the output buffer -
408 * Note, we may have incomplete half-sent frames in here.
410 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
412 /* Lets see how much we can send out */
413 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
415 /* Check for errors, and advance the buffer if any was sent */
417 session->outbuf = session->outbuf.substr(ret);
426 session->outbuf = "";
432 session->outbuf = "";
437 /* ALL LIES the lot of it, we havent really written
438 * this amount, but the layer above doesnt need to know.
443 void CloseSession(izip_session* session)
445 if (session->status = IZIP_OPEN)
447 session->status = IZIP_CLOSED;
448 session->outbuf = "";
449 delete session->inbuf;
455 class ModuleZLibFactory : public ModuleFactory
466 virtual Module * CreateModule(InspIRCd* Me)
468 return new ModuleZLib(Me);
473 extern "C" void * init_module( void )
475 return new ModuleZLibFactory;