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 /* Maximum transfer size per read operation */
39 const unsigned int CHUNK = 128 * 1024;
41 /** Represents an zipped connections extra data
43 class izip_session : public classbase
46 z_stream c_stream; /* compression stream */
47 z_stream d_stream; /* uncompress stream */
48 izip_status status; /* Connection status */
49 std::string outbuf; /* Holds output buffer (compressed) */
50 std::string inbuf; /* Holds input buffer (compressed) */
53 class ModuleZLib : public Module
55 izip_session* sessions;
57 /* Used for stats z extensions */
58 float total_out_compressed;
59 float total_in_compressed;
60 float total_out_uncompressed;
61 float total_in_uncompressed;
63 /* Used for reading data from the wire.
64 * We need a smaller buffer than CHUNK, else we could read more data
65 * from the wire than we can pass to the socket code.
68 unsigned int read_buffer_size;
71 ModuleZLib(InspIRCd* Me)
74 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
76 sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
77 for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
78 sessions[i].status = IZIP_CLOSED;
80 total_out_compressed = total_in_compressed = 0;
81 total_out_uncompressed = total_in_uncompressed = 0;
82 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnStats, I_OnRequest };
83 ServerInstance->Modules->Attach(eventlist, this, 7);
85 read_buffer_size = ServerInstance->Config->NetBufferSize / 4;
86 read_buffer = new char[read_buffer_size];
91 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
96 virtual Version GetVersion()
98 return Version("$Id$", VF_VENDOR, API_VERSION);
102 /* Handle BufferedSocketHook API requests */
103 virtual const char* OnRequest(Request* request)
105 ISHRequest* ISR = (ISHRequest*)request;
106 if (strcmp("IS_NAME", request->GetId()) == 0)
111 else if (strcmp("IS_HOOK", request->GetId()) == 0)
113 /* Attach to an inspsocket */
114 const char* ret = "OK";
117 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? "OK" : NULL;
119 catch (ModuleException& e)
125 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
127 /* Detach from an inspsocket */
128 return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? "OK" : NULL;
130 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
132 /* Check for completion of handshake
133 * (actually, this module doesnt handshake)
137 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
139 /* Attach certificate data to the inspsocket
140 * (this module doesnt do that, either)
147 /* Handle stats z (misc stats) */
148 virtual int OnStats(char symbol, User* user, string_list &results)
152 std::string sn = ServerInstance->Config->ServerName;
154 /* Yeah yeah, i know, floats are ew.
155 * We used them here because we'd be casting to float anyway to do this maths,
156 * and also only floating point numbers can deal with the pretty large numbers
157 * involved in the total throughput of a server over a large period of time.
158 * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
159 * can still hold more.
161 float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
162 float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
164 float total_compressed = total_in_compressed + total_out_compressed;
165 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
167 float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
169 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
171 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
172 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
173 sprintf(combined_ratio, "%3.2f%%", total_r);
175 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
176 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
177 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
178 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
179 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
180 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
181 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
188 virtual void OnRawSocketConnect(int fd)
190 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
193 izip_session* session = &sessions[fd];
195 /* allocate state and buffers */
196 session->status = IZIP_OPEN;
198 /* Just in case... */
199 session->outbuf.clear();
201 session->c_stream.zalloc = (alloc_func)0;
202 session->c_stream.zfree = (free_func)0;
203 session->c_stream.opaque = (voidpf)0;
205 session->d_stream.zalloc = (alloc_func)0;
206 session->d_stream.zfree = (free_func)0;
207 session->d_stream.opaque = (voidpf)0;
209 /* If we cant call this, well, we're boned. */
210 if (inflateInit(&session->d_stream) != Z_OK)
212 session->status = IZIP_CLOSED;
217 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
219 inflateEnd(&session->d_stream);
220 session->status = IZIP_CLOSED;
225 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
227 /* Nothing special needs doing here compared to connect() */
228 OnRawSocketConnect(fd);
231 virtual void OnRawSocketClose(int fd)
233 CloseSession(&sessions[fd]);
236 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
238 /* Find the sockets session */
239 izip_session* session = &sessions[fd];
241 if (session->status == IZIP_CLOSED)
244 /* Read read_buffer_size bytes at a time to the buffer (usually 128k) */
245 readresult = read(fd, read_buffer, read_buffer_size);
247 /* Did we get anything? */
251 total_in_compressed += readresult;
253 /* Copy the compressed data into out input buffer */
254 session->inbuf.append(read_buffer, readresult);
255 size_t in_len = session->inbuf.length();
257 /* Prepare decompression */
258 session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
259 session->d_stream.avail_in = in_len;
261 session->d_stream.next_out = (Bytef*)buffer;
262 /* Last byte is reserved for NULL terminating that beast */
263 session->d_stream.avail_out = count - 1;
265 /* Z_SYNC_FLUSH: Do as much as possible */
266 int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
267 /* TODO CloseStream() in here at random places */
272 /* This is one of the 'not supposed to happen' things.
273 * Memory corruption, anyone?
275 Error(session, "General Error. This is not supposed to happen :/");
278 Error(session, "Decompression failed, malformed data");
281 Error(session, "Out of memory");
284 /* This one is non-fatal, buffer is just full
285 * (can't happen here).
287 Error(session, "Internal error. This is not supposed to happen.");
290 /* This module *never* generates these :/ */
291 Error(session, "End-of-stream marker received");
296 /* NO WAI! This can't happen. All errors are handled above. */
297 Error(session, "Unknown error");
306 /* Update the inbut buffer */
307 unsigned int input_compressed = in_len - session->d_stream.avail_in;
308 session->inbuf = session->inbuf.substr(input_compressed);
310 /* Update counters (Old size - new size) */
311 unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
312 total_in_uncompressed += uncompressed_length;
314 /* Null-terminate the buffer -- this doesnt harm binary data */
315 buffer[uncompressed_length] = 0;
317 /* Set the read size to the correct total size */
318 readresult = uncompressed_length;
323 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
325 izip_session* session = &sessions[fd];
327 if (!count) /* Nothing to do! */
330 if(session->status != IZIP_OPEN)
331 /* Seriously, wtf? */
334 unsigned char compr[CHUNK];
337 /* This loop is really only supposed to run once, but in case 'compr'
338 * is filled up somehow we are prepared to handle this situation.
340 unsigned int offset = 0;
343 /* Prepare compression */
344 session->c_stream.next_in = (Bytef*)buffer + offset;
345 session->c_stream.avail_in = count - offset;
347 session->c_stream.next_out = compr;
348 session->c_stream.avail_out = CHUNK;
350 /* Compress the text */
351 ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
352 /* TODO CloseStream() in here at random places */
358 /* This one is non-fatal, buffer is just full
359 * (can't happen here).
361 Error(session, "Internal error. This is not supposed to happen.");
364 /* This is one of the 'not supposed to happen' things.
365 * Memory corruption, anyone?
367 Error(session, "General Error. This is also not supposed to happen.");
370 Error(session, "Unknown error");
377 /* Space before - space after stuff was added to this */
378 unsigned int compressed = CHUNK - session->c_stream.avail_out;
379 unsigned int uncompressed = count - session->c_stream.avail_in;
381 /* Make it skip the data which was compressed already */
382 offset += uncompressed;
385 total_out_uncompressed += uncompressed;
386 total_out_compressed += compressed;
388 /* Add compressed to the output buffer */
389 session->outbuf.append((const char*)compr, compressed);
390 } while (session->c_stream.avail_in != 0);
392 /* Lets see how much we can send out */
393 ret = write(fd, session->outbuf.data(), session->outbuf.length());
395 /* Check for errors, and advance the buffer if any was sent */
397 session->outbuf = session->outbuf.substr(ret);
404 session->outbuf.clear();
405 /* TODO pass errors down? */
410 /* ALL LIES the lot of it, we havent really written
411 * this amount, but the layer above doesnt need to know.
416 void Error(izip_session* session, const std::string &text)
418 ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
421 void CloseSession(izip_session* session)
423 if (session->status == IZIP_OPEN)
425 session->status = IZIP_CLOSED;
426 session->outbuf.clear();
427 inflateEnd(&session->d_stream);
428 deflateEnd(&session->c_stream);
434 MODULE_INIT(ModuleZLib)