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"
25 /* $ModDesc: Provides zlib link support for servers */
26 /* $LinkerFlags: -lz */
27 /* $ModDep: transport.h */
30 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
31 * a flush after each chunk. A frame may contain multiple lines
32 * and should be treated as raw binary data.
35 /* Status of a connection */
36 enum izip_status { IZIP_CLOSED = 0, IZIP_OPEN };
38 /** Represents an zipped connections extra data
40 class izip_session : public classbase
43 z_stream c_stream; /* compression stream */
44 z_stream d_stream; /* uncompress stream */
45 izip_status status; /* Connection status */
46 std::string outbuf; /* Holds output buffer (compressed) */
47 std::string inbuf; /* Holds input buffer (compressed) */
50 class ModuleZLib : public Module
52 izip_session* sessions;
54 /* Used for stats z extensions */
55 float total_out_compressed;
56 float total_in_compressed;
57 float total_out_uncompressed;
58 float total_in_uncompressed;
60 /* Used for reading data from the wire and compressing data to. */
62 unsigned int net_buffer_size;
65 ModuleZLib(InspIRCd* Me)
68 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
70 sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
71 for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
72 sessions[i].status = IZIP_CLOSED;
74 total_out_compressed = total_in_compressed = 0;
75 total_out_uncompressed = total_in_uncompressed = 0;
76 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnStats, I_OnRequest };
77 ServerInstance->Modules->Attach(eventlist, this, 7);
79 // Allocate a buffer which is used for reading and writing data
80 net_buffer_size = ServerInstance->Config->NetBufferSize;
81 net_buffer = new char[net_buffer_size];
86 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
91 virtual Version GetVersion()
93 return Version("$Id$", VF_VENDOR, API_VERSION);
97 /* Handle BufferedSocketHook API requests */
98 virtual const char* OnRequest(Request* request)
100 ISHRequest* ISR = (ISHRequest*)request;
101 if (strcmp("IS_NAME", request->GetId()) == 0)
106 else if (strcmp("IS_HOOK", request->GetId()) == 0)
108 /* Attach to an inspsocket */
109 const char* ret = "OK";
112 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
114 catch (ModuleException& e)
120 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
122 /* Detach from an inspsocket */
123 return ISR->Sock->DelIOHook() ? "OK" : NULL;
125 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
127 /* Check for completion of handshake
128 * (actually, this module doesnt handshake)
132 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
134 /* Attach certificate data to the inspsocket
135 * (this module doesnt do that, either)
142 /* Handle stats z (misc stats) */
143 virtual int OnStats(char symbol, User* user, string_list &results)
147 std::string sn = ServerInstance->Config->ServerName;
149 /* Yeah yeah, i know, floats are ew.
150 * We used them here because we'd be casting to float anyway to do this maths,
151 * and also only floating point numbers can deal with the pretty large numbers
152 * involved in the total throughput of a server over a large period of time.
153 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
154 * can still hold more.
156 float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
157 float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
159 float total_compressed = total_in_compressed + total_out_compressed;
160 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
162 float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
164 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
166 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
167 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
168 sprintf(combined_ratio, "%3.2f%%", total_r);
170 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
171 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
172 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
173 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
174 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_original_outbound_traffic = "+outbound_ratio);
175 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_orignal_inbound_traffic = "+inbound_ratio);
176 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS total_size_of_original_traffic = "+combined_ratio);
183 virtual void OnRawSocketConnect(int fd)
185 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
188 izip_session* session = &sessions[fd];
190 /* Just in case... */
191 session->outbuf.clear();
193 session->c_stream.zalloc = (alloc_func)0;
194 session->c_stream.zfree = (free_func)0;
195 session->c_stream.opaque = (voidpf)0;
197 session->d_stream.zalloc = (alloc_func)0;
198 session->d_stream.zfree = (free_func)0;
199 session->d_stream.opaque = (voidpf)0;
201 /* If we cant call this, well, we're boned. */
202 if (inflateInit(&session->d_stream) != Z_OK)
204 session->status = IZIP_CLOSED;
209 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
211 inflateEnd(&session->d_stream);
212 session->status = IZIP_CLOSED;
216 /* Just in case, do this last */
217 session->status = IZIP_OPEN;
220 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
222 /* Nothing special needs doing here compared to connect() */
223 OnRawSocketConnect(fd);
226 virtual void OnRawSocketClose(int fd)
228 CloseSession(&sessions[fd]);
231 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
233 /* Find the sockets session */
234 izip_session* session = &sessions[fd];
236 if (session->status == IZIP_CLOSED)
239 if (session->inbuf.length())
241 /* Our input buffer is filling up. This is *BAD*.
242 * We can't return more data than fits into buffer
243 * (count bytes), so we will generate another read
244 * event on purpose by *NOT* reading from 'fd' at all
251 /* Read read_buffer_size bytes at a time to the buffer (usually 2.5k) */
252 readresult = read(fd, net_buffer, net_buffer_size);
254 total_in_compressed += readresult;
256 /* Copy the compressed data into our input buffer */
257 session->inbuf.append(net_buffer, readresult);
260 size_t in_len = session->inbuf.length();
262 /* Do we have anything to do? */
266 /* Prepare decompression */
267 session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
268 session->d_stream.avail_in = in_len;
270 session->d_stream.next_out = (Bytef*)buffer;
271 /* Last byte is reserved for NULL terminating that beast */
272 session->d_stream.avail_out = count - 1;
274 /* Z_SYNC_FLUSH: Do as much as possible */
275 int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
276 /* TODO CloseStream() in here at random places */
281 /* This is one of the 'not supposed to happen' things.
282 * Memory corruption, anyone?
284 Error(session, "General Error. This is not supposed to happen :/");
287 Error(session, "Decompression failed, malformed data");
290 Error(session, "Out of memory");
293 /* This one is non-fatal, buffer is just full
294 * (can't happen here).
296 Error(session, "Internal error. This is not supposed to happen.");
299 /* This module *never* generates these :/ */
300 Error(session, "End-of-stream marker received");
305 /* NO WAI! This can't happen. All errors are handled above. */
306 Error(session, "Unknown error");
315 /* Update the inbut buffer */
316 unsigned int input_compressed = in_len - session->d_stream.avail_in;
317 session->inbuf = session->inbuf.substr(input_compressed);
319 /* Update counters (Old size - new size) */
320 unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
321 total_in_uncompressed += uncompressed_length;
323 /* Null-terminate the buffer -- this doesnt harm binary data */
324 buffer[uncompressed_length] = 0;
326 /* Set the read size to the correct total size */
327 readresult = uncompressed_length;
332 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
334 izip_session* session = &sessions[fd];
336 if (!count) /* Nothing to do! */
339 if(session->status != IZIP_OPEN)
340 /* Seriously, wtf? */
345 /* This loop is really only supposed to run once, but in case 'compr'
346 * is filled up somehow we are prepared to handle this situation.
348 unsigned int offset = 0;
351 /* Prepare compression */
352 session->c_stream.next_in = (Bytef*)buffer + offset;
353 session->c_stream.avail_in = count - offset;
355 session->c_stream.next_out = (Bytef*)net_buffer;
356 session->c_stream.avail_out = net_buffer_size;
358 /* Compress the text */
359 ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
360 /* TODO CloseStream() in here at random places */
366 /* This one is non-fatal, buffer is just full
367 * (can't happen here).
369 Error(session, "Internal error. This is not supposed to happen.");
372 /* This is one of the 'not supposed to happen' things.
373 * Memory corruption, anyone?
375 Error(session, "General Error. This is also not supposed to happen.");
378 Error(session, "Unknown error");
385 /* Space before - space after stuff was added to this */
386 unsigned int compressed = net_buffer_size - session->c_stream.avail_out;
387 unsigned int uncompressed = count - session->c_stream.avail_in;
389 /* Make it skip the data which was compressed already */
390 offset += uncompressed;
393 total_out_uncompressed += uncompressed;
394 total_out_compressed += compressed;
396 /* Add compressed to the output buffer */
397 session->outbuf.append((const char*)net_buffer, compressed);
398 } while (session->c_stream.avail_in != 0);
400 /* Lets see how much we can send out */
401 ret = write(fd, session->outbuf.data(), session->outbuf.length());
403 /* Check for errors, and advance the buffer if any was sent */
405 session->outbuf = session->outbuf.substr(ret);
412 session->outbuf.clear();
417 /* ALL LIES the lot of it, we havent really written
418 * this amount, but the layer above doesnt need to know.
423 void Error(izip_session* session, const std::string &text)
425 ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
428 void CloseSession(izip_session* session)
430 if (session->status == IZIP_OPEN)
432 session->status = IZIP_CLOSED;
433 session->outbuf.clear();
434 inflateEnd(&session->d_stream);
435 deflateEnd(&session->c_stream);
441 MODULE_INIT(ModuleZLib)