1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include "transport.h"
19 /* $ModDesc: Provides zlib link support for servers */
20 /* $LinkerFlags: -lz */
21 /* $ModDep: transport.h */
24 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
25 * a flush after each chunk. A frame may contain multiple lines
26 * and should be treated as raw binary data.
29 /* Status of a connection */
30 enum izip_status { IZIP_CLOSED = 0, IZIP_OPEN };
32 /** Represents an zipped connections extra data
34 class izip_session : public classbase
37 z_stream c_stream; /* compression stream */
38 z_stream d_stream; /* uncompress stream */
39 izip_status status; /* Connection status */
40 std::string outbuf; /* Holds output buffer (compressed) */
41 std::string inbuf; /* Holds input buffer (compressed) */
44 class ModuleZLib : public Module
46 izip_session* sessions;
48 /* Used for stats z extensions */
49 float total_out_compressed;
50 float total_in_compressed;
51 float total_out_uncompressed;
52 float total_in_uncompressed;
54 /* Used for reading data from the wire and compressing data to. */
56 unsigned int net_buffer_size;
59 ModuleZLib(InspIRCd* Me)
62 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
64 sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
65 for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
66 sessions[i].status = IZIP_CLOSED;
68 total_out_compressed = total_in_compressed = 0;
69 total_out_uncompressed = total_in_uncompressed = 0;
70 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnStats, I_OnRequest };
71 ServerInstance->Modules->Attach(eventlist, this, 7);
73 // Allocate a buffer which is used for reading and writing data
74 net_buffer_size = ServerInstance->Config->NetBufferSize;
75 net_buffer = new char[net_buffer_size];
80 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
85 virtual Version GetVersion()
87 return Version("$Id$", VF_VENDOR, API_VERSION);
91 /* Handle BufferedSocketHook API requests */
92 virtual const char* OnRequest(Request* request)
94 ISHRequest* ISR = (ISHRequest*)request;
95 if (strcmp("IS_NAME", request->GetId()) == 0)
100 else if (strcmp("IS_HOOK", request->GetId()) == 0)
102 /* Attach to an inspsocket */
103 const char* ret = "OK";
106 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
108 catch (ModuleException& e)
114 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
116 /* Detach from an inspsocket */
117 return ISR->Sock->DelIOHook() ? "OK" : NULL;
119 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
121 /* Check for completion of handshake
122 * (actually, this module doesnt handshake)
126 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
128 /* Attach certificate data to the inspsocket
129 * (this module doesnt do that, either)
136 /* Handle stats z (misc stats) */
137 virtual int OnStats(char symbol, User* user, string_list &results)
141 std::string sn = ServerInstance->Config->ServerName;
143 /* Yeah yeah, i know, floats are ew.
144 * We used them here because we'd be casting to float anyway to do this maths,
145 * and also only floating point numbers can deal with the pretty large numbers
146 * involved in the total throughput of a server over a large period of time.
147 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
148 * can still hold more.
150 float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
151 float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
153 float total_compressed = total_in_compressed + total_out_compressed;
154 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
156 float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
158 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
160 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
161 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
162 sprintf(combined_ratio, "%3.2f%%", total_r);
164 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
165 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
166 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
167 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
168 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_original_outbound_traffic = "+outbound_ratio);
169 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_orignal_inbound_traffic = "+inbound_ratio);
170 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS total_size_of_original_traffic = "+combined_ratio);
177 virtual void OnRawSocketConnect(int fd)
179 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
182 izip_session* session = &sessions[fd];
184 /* Just in case... */
185 session->outbuf.clear();
187 session->c_stream.zalloc = (alloc_func)0;
188 session->c_stream.zfree = (free_func)0;
189 session->c_stream.opaque = (voidpf)0;
191 session->d_stream.zalloc = (alloc_func)0;
192 session->d_stream.zfree = (free_func)0;
193 session->d_stream.opaque = (voidpf)0;
195 /* If we cant call this, well, we're boned. */
196 if (inflateInit(&session->d_stream) != Z_OK)
198 session->status = IZIP_CLOSED;
203 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
205 inflateEnd(&session->d_stream);
206 session->status = IZIP_CLOSED;
210 /* Just in case, do this last */
211 session->status = IZIP_OPEN;
214 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
216 /* Nothing special needs doing here compared to connect() */
217 OnRawSocketConnect(fd);
220 virtual void OnRawSocketClose(int fd)
222 CloseSession(&sessions[fd]);
225 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
227 /* Find the sockets session */
228 izip_session* session = &sessions[fd];
230 if (session->status == IZIP_CLOSED)
233 if (session->inbuf.length())
235 /* Our input buffer is filling up. This is *BAD*.
236 * We can't return more data than fits into buffer
237 * (count bytes), so we will generate another read
238 * event on purpose by *NOT* reading from 'fd' at all
245 /* Read read_buffer_size bytes at a time to the buffer (usually 2.5k) */
246 readresult = read(fd, net_buffer, net_buffer_size);
248 total_in_compressed += readresult;
250 /* Copy the compressed data into our input buffer */
251 session->inbuf.append(net_buffer, readresult);
254 size_t in_len = session->inbuf.length();
256 /* Do we have anything to do? */
260 /* Prepare decompression */
261 session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
262 session->d_stream.avail_in = in_len;
264 session->d_stream.next_out = (Bytef*)buffer;
265 /* Last byte is reserved for NULL terminating that beast */
266 session->d_stream.avail_out = count - 1;
268 /* Z_SYNC_FLUSH: Do as much as possible */
269 int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
270 /* TODO CloseStream() in here at random places */
275 /* This is one of the 'not supposed to happen' things.
276 * Memory corruption, anyone?
278 Error(session, "General Error. This is not supposed to happen :/");
281 Error(session, "Decompression failed, malformed data");
284 Error(session, "Out of memory");
287 /* This one is non-fatal, buffer is just full
288 * (can't happen here).
290 Error(session, "Internal error. This is not supposed to happen.");
293 /* This module *never* generates these :/ */
294 Error(session, "End-of-stream marker received");
299 /* NO WAI! This can't happen. All errors are handled above. */
300 Error(session, "Unknown error");
309 /* Update the inbut buffer */
310 unsigned int input_compressed = in_len - session->d_stream.avail_in;
311 session->inbuf = session->inbuf.substr(input_compressed);
313 /* Update counters (Old size - new size) */
314 unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
315 total_in_uncompressed += uncompressed_length;
317 /* Null-terminate the buffer -- this doesnt harm binary data */
318 buffer[uncompressed_length] = 0;
320 /* Set the read size to the correct total size */
321 readresult = uncompressed_length;
326 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
328 izip_session* session = &sessions[fd];
330 if (!count) /* Nothing to do! */
333 if(session->status != IZIP_OPEN)
334 /* Seriously, wtf? */
339 /* This loop is really only supposed to run once, but in case 'compr'
340 * is filled up somehow we are prepared to handle this situation.
342 unsigned int offset = 0;
345 /* Prepare compression */
346 session->c_stream.next_in = (Bytef*)buffer + offset;
347 session->c_stream.avail_in = count - offset;
349 session->c_stream.next_out = (Bytef*)net_buffer;
350 session->c_stream.avail_out = net_buffer_size;
352 /* Compress the text */
353 ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
354 /* TODO CloseStream() in here at random places */
360 /* This one is non-fatal, buffer is just full
361 * (can't happen here).
363 Error(session, "Internal error. This is not supposed to happen.");
366 /* This is one of the 'not supposed to happen' things.
367 * Memory corruption, anyone?
369 Error(session, "General Error. This is also not supposed to happen.");
372 Error(session, "Unknown error");
379 /* Space before - space after stuff was added to this */
380 unsigned int compressed = net_buffer_size - session->c_stream.avail_out;
381 unsigned int uncompressed = count - session->c_stream.avail_in;
383 /* Make it skip the data which was compressed already */
384 offset += uncompressed;
387 total_out_uncompressed += uncompressed;
388 total_out_compressed += compressed;
390 /* Add compressed to the output buffer */
391 session->outbuf.append((const char*)net_buffer, compressed);
392 } while (session->c_stream.avail_in != 0);
394 /* Lets see how much we can send out */
395 ret = write(fd, session->outbuf.data(), session->outbuf.length());
397 /* Check for errors, and advance the buffer if any was sent */
399 session->outbuf = session->outbuf.substr(ret);
406 session->outbuf.clear();
411 /* ALL LIES the lot of it, we havent really written
412 * this amount, but the layer above doesnt need to know.
417 void Error(izip_session* session, const std::string &text)
419 ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
422 void CloseSession(izip_session* session)
424 if (session->status == IZIP_OPEN)
426 session->status = IZIP_CLOSED;
427 session->outbuf.clear();
428 inflateEnd(&session->d_stream);
429 deflateEnd(&session->c_stream);
435 MODULE_INIT(ModuleZLib)