1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
21 #include "transport.h"
23 /* $ModDesc: Provides zlib link support for servers */
24 /* $LinkerFlags: -lz */
25 /* $ModDep: transport.h */
28 * Compressed data is transmitted across the link in the following format:
31 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
33 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
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.
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.
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.
48 /* Status of a connection */
49 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
51 /* Maximum transfer size per read operation */
52 const unsigned int CHUNK = 128 * 1024;
54 /* This class manages a compressed chunk of data preceeded by
57 * It can handle having multiple chunks of data in the buffer
60 class CountedBuffer : public classbase
62 std::string buffer; /* Current buffer contents */
63 unsigned int amount_expected; /* Amount of data expected */
70 /** Adds arbitrary compressed data to the buffer.
71 * - Binsry safe, of course.
73 void AddData(unsigned char* data, int data_length)
75 buffer.append((const char*)data, data_length);
76 this->NextFrameSize();
79 /** Works out the size of the next compressed frame
83 if ((!amount_expected) && (buffer.length() >= 4))
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.
91 amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);
92 buffer = buffer.substr(4);
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.
101 int GetFrame(unsigned char* frame, int maxsize)
105 /* We know how much we're expecting...
106 * Do we have enough yet?
108 if (buffer.length() >= amount_expected)
111 for (unsigned int i = 0; i < amount_expected; i++, j++)
112 frame[i] = buffer[i];
114 buffer = buffer.substr(j);
120 /* Not enough for a frame yet, COME AGAIN! */
125 /** Represents an zipped connections extra data
127 class izip_session : public classbase
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 */
138 class ModuleZLib : public Module
140 izip_session sessions[MAX_DESCRIPTORS];
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;
150 ModuleZLib(InspIRCd* Me)
153 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
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);
161 virtual ~ModuleZLib()
163 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
166 virtual Version GetVersion()
168 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
171 void Implements(char* List)
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;
177 /* Handle BufferedSocketHook API requests */
178 virtual char* OnRequest(Request* request)
180 ISHRequest* ISR = (ISHRequest*)request;
181 if (strcmp("IS_NAME", request->GetId()) == 0)
186 else if (strcmp("IS_HOOK", request->GetId()) == 0)
188 /* Attach to an inspsocket */
192 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
194 catch (ModuleException& e)
200 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
202 /* Detatch from an inspsocket */
203 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
205 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
207 /* Check for completion of handshake
208 * (actually, this module doesnt handshake)
212 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
214 /* Attach certificate data to the inspsocket
215 * (this module doesnt do that, either)
222 /* Handle stats z (misc stats) */
223 virtual int OnStats(char symbol, User* user, string_list &results)
227 std::string sn = ServerInstance->Config->ServerName;
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.
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);
239 float total_compressed = total_in_compressed + total_out_compressed;
240 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
242 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
244 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
246 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
247 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
248 sprintf(combined_ratio, "%3.2f%%", total_r);
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);
263 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
265 izip_session* session = &sessions[fd];
267 /* allocate state and buffers */
269 session->status = IZIP_OPEN;
270 session->inbuf = new CountedBuffer();
272 session->c_stream.zalloc = (alloc_func)0;
273 session->c_stream.zfree = (free_func)0;
274 session->c_stream.opaque = (voidpf)0;
276 session->d_stream.zalloc = (alloc_func)0;
277 session->d_stream.zfree = (free_func)0;
278 session->d_stream.opaque = (voidpf)0;
281 virtual void OnRawSocketConnect(int fd)
283 /* Nothing special needs doing here compared to accept() */
284 OnRawSocketAccept(fd, "", 0);
287 virtual void OnRawSocketClose(int fd)
289 CloseSession(&sessions[fd]);
292 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
294 /* Find the sockets session */
295 izip_session* session = &sessions[fd];
297 if (session->status == IZIP_CLOSED)
300 unsigned char compr[CHUNK + 4];
301 unsigned int offset = 0;
302 unsigned int total_size = 0;
304 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
305 readresult = read(fd, compr, CHUNK);
307 /* Did we get anything? */
310 /* Add it to the frame queue */
311 session->inbuf->AddData(compr, readresult);
312 total_in_compressed += readresult;
314 /* Parse all completed frames */
316 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
318 session->d_stream.next_in = (Bytef*)compr;
319 session->d_stream.avail_in = 0;
320 session->d_stream.next_out = (Bytef*)(buffer + offset);
322 /* If we cant call this, well, we're boned. */
323 if (inflateInit(&session->d_stream) != Z_OK)
326 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
328 session->d_stream.avail_in = session->d_stream.avail_out = 1;
329 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
333 /* Stick a fork in me, i'm done */
334 inflateEnd(&session->d_stream);
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;
342 /* Null-terminate the buffer -- this doesnt harm binary data */
343 buffer[total_size] = 0;
345 /* Set the read size to the correct total size */
346 readresult = total_size;
349 return (readresult > 0);
352 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
354 izip_session* session = &sessions[fd];
357 if (!count) /* Nothing to do! */
360 if(session->status != IZIP_OPEN)
362 /* Seriously, wtf? */
363 CloseSession(session);
367 unsigned char compr[CHUNK + 4];
369 /* Gentlemen, start your engines! */
370 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
372 CloseSession(session);
376 /* Set buffer sizes (we reserve 4 bytes at the start of the
377 * buffer for the length counters)
379 session->c_stream.next_in = (Bytef*)buffer;
380 session->c_stream.next_out = compr + 4;
382 /* Compress the text */
383 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
385 session->c_stream.avail_in = session->c_stream.avail_out = 1;
386 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
388 CloseSession(session);
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);
396 total_out_uncompressed += ocount;
397 total_out_compressed += session->c_stream.total_out;
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);
405 /* Add compressed data plus leading length to the output buffer -
406 * Note, we may have incomplete half-sent frames in here.
408 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
410 /* Lets see how much we can send out */
411 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
413 /* Check for errors, and advance the buffer if any was sent */
415 session->outbuf = session->outbuf.substr(ret);
424 session->outbuf.clear();
430 session->outbuf.clear();
435 /* ALL LIES the lot of it, we havent really written
436 * this amount, but the layer above doesnt need to know.
441 void CloseSession(izip_session* session)
443 if (session->status == IZIP_OPEN)
445 session->status = IZIP_CLOSED;
446 session->outbuf.clear();
447 delete session->inbuf;
453 MODULE_INIT(ModuleZLib)