1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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, 2, 0, 0, VF_VENDOR, API_VERSION);
172 /* Handle BufferedSocketHook API requests */
173 virtual const char* OnRequest(Request* request)
175 ISHRequest* ISR = (ISHRequest*)request;
176 if (strcmp("IS_NAME", request->GetId()) == 0)
181 else if (strcmp("IS_HOOK", request->GetId()) == 0)
183 /* Attach to an inspsocket */
184 const char* ret = "OK";
187 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
189 catch (ModuleException& e)
195 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
197 /* Detatch from an inspsocket */
198 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
200 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
202 /* Check for completion of handshake
203 * (actually, this module doesnt handshake)
207 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
209 /* Attach certificate data to the inspsocket
210 * (this module doesnt do that, either)
217 /* Handle stats z (misc stats) */
218 virtual int OnStats(char symbol, User* user, string_list &results)
222 std::string sn = ServerInstance->Config->ServerName;
224 /* Yeah yeah, i know, floats are ew.
225 * We used them here because we'd be casting to float anyway to do this maths,
226 * and also only floating point numbers can deal with the pretty large numbers
227 * involved in the total throughput of a server over a large period of time.
228 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
229 * can still hold more.
231 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
232 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
234 float total_compressed = total_in_compressed + total_out_compressed;
235 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
237 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
239 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
241 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
242 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
243 sprintf(combined_ratio, "%3.2f%%", total_r);
245 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
246 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
247 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
248 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
249 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
250 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
251 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
258 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
260 izip_session* session = &sessions[fd];
262 /* allocate state and buffers */
264 session->status = IZIP_OPEN;
265 session->inbuf = new CountedBuffer();
267 session->c_stream.zalloc = (alloc_func)0;
268 session->c_stream.zfree = (free_func)0;
269 session->c_stream.opaque = (voidpf)0;
271 session->d_stream.zalloc = (alloc_func)0;
272 session->d_stream.zfree = (free_func)0;
273 session->d_stream.opaque = (voidpf)0;
276 virtual void OnRawSocketConnect(int fd)
278 /* Nothing special needs doing here compared to accept() */
279 OnRawSocketAccept(fd, "", 0);
282 virtual void OnRawSocketClose(int fd)
284 CloseSession(&sessions[fd]);
287 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
289 /* Find the sockets session */
290 izip_session* session = &sessions[fd];
292 if (session->status == IZIP_CLOSED)
295 unsigned char compr[CHUNK + 4];
296 unsigned int offset = 0;
297 unsigned int total_size = 0;
299 /* Read CHUNK bytes at a time to the buffer (usually 128k) */
300 readresult = read(fd, compr, CHUNK);
302 /* Did we get anything? */
305 /* Add it to the frame queue */
306 session->inbuf->AddData(compr, readresult);
307 total_in_compressed += readresult;
309 /* Parse all completed frames */
311 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
313 session->d_stream.next_in = (Bytef*)compr;
314 session->d_stream.avail_in = 0;
315 session->d_stream.next_out = (Bytef*)(buffer + offset);
317 /* If we cant call this, well, we're boned. */
318 if (inflateInit(&session->d_stream) != Z_OK)
321 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
323 session->d_stream.avail_in = session->d_stream.avail_out = 1;
324 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
328 /* Stick a fork in me, i'm done */
329 inflateEnd(&session->d_stream);
331 /* Update counters and offsets */
332 total_size += session->d_stream.total_out;
333 total_in_uncompressed += session->d_stream.total_out;
334 offset += session->d_stream.total_out;
337 /* Null-terminate the buffer -- this doesnt harm binary data */
338 buffer[total_size] = 0;
340 /* Set the read size to the correct total size */
341 readresult = total_size;
344 return (readresult > 0);
347 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
349 izip_session* session = &sessions[fd];
352 if (!count) /* Nothing to do! */
355 if(session->status != IZIP_OPEN)
357 /* Seriously, wtf? */
358 CloseSession(session);
362 unsigned char compr[CHUNK + 4];
364 /* Gentlemen, start your engines! */
365 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
367 CloseSession(session);
371 /* Set buffer sizes (we reserve 4 bytes at the start of the
372 * buffer for the length counters)
374 session->c_stream.next_in = (Bytef*)buffer;
375 session->c_stream.next_out = compr + 4;
377 /* Compress the text */
378 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
380 session->c_stream.avail_in = session->c_stream.avail_out = 1;
381 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
383 CloseSession(session);
387 /* Finish the stream */
388 for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);
389 deflateEnd(&session->c_stream);
391 total_out_uncompressed += ocount;
392 total_out_compressed += session->c_stream.total_out;
394 /** Assemble the frame length onto the frame, in network byte order */
395 compr[0] = (session->c_stream.total_out >> 24);
396 compr[1] = (session->c_stream.total_out >> 16);
397 compr[2] = (session->c_stream.total_out >> 8);
398 compr[3] = (session->c_stream.total_out & 0xFF);
400 /* Add compressed data plus leading length to the output buffer -
401 * Note, we may have incomplete half-sent frames in here.
403 session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);
405 /* Lets see how much we can send out */
406 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
408 /* Check for errors, and advance the buffer if any was sent */
410 session->outbuf = session->outbuf.substr(ret);
419 session->outbuf.clear();
425 session->outbuf.clear();
430 /* ALL LIES the lot of it, we havent really written
431 * this amount, but the layer above doesnt need to know.
436 void CloseSession(izip_session* session)
438 if (session->status == IZIP_OPEN)
440 session->status = IZIP_CLOSED;
441 session->outbuf.clear();
442 delete session->inbuf;
448 MODULE_INIT(ModuleZLib)