1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
22 #include "inspircd_config.h"
23 #include "configreader.h"
32 #include "transport.h"
34 /* $ModDesc: Provides zlib link support for servers */
35 /* $LinkerFlags: -lz */
36 /* $ModDep: transport.h */
39 * Compressed data is transmitted across the link in the following format:
42 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
44 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
46 * Where: n is the size of a frame, in network byte order, 4 bytes.
47 * Z0 through Zn are Zlib compressed data, n bytes in length.
49 * If the module fails to read the entire frame, then it will buffer
50 * the portion of the last frame it received, then attempt to read
51 * the next part of the frame next time a write notification arrives.
53 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
54 * a flush after each frame. A frame may contain multiple lines
55 * and should be treated as raw binary data.
59 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
61 const unsigned int CHUNK = 128 * 1024;
63 class CountedBuffer : public classbase
65 std::deque<unsigned char> buffer; /* Current buffer contents */
66 unsigned int amount_expected; /* Amount of data expected */
73 void AddData(unsigned char* data, int data_length)
75 for (int i = 0; i < data_length; i++)
76 buffer.push_back(data[i]);
78 this->NextFrameSize();
83 if ((!amount_expected) && (buffer.size() >= 4))
85 /* We have enough to read an int */
87 for (int i = 0; i < 4; i++)
89 sz[i] = buffer.front();
93 amount_expected = ntohl(*size);
97 int GetFrame(unsigned char* frame, int maxsize)
101 /* We know how much we're expecting...
102 * Do we have enough yet?
104 if (buffer.size() >= amount_expected)
107 for (unsigned int i = 0; i < amount_expected; i++, j++)
109 frame[i] = buffer.front();
119 /* Not enough for a frame yet, COME AGAIN! */
124 /** Represents an ZIP user's extra data
126 class izip_session : public classbase
129 z_stream c_stream; /* compression stream */
130 z_stream d_stream; /* decompress stream */
133 CountedBuffer* inbuf;
137 class ModuleZLib : public Module
139 izip_session sessions[MAX_DESCRIPTORS];
140 float total_out_compressed;
141 float total_in_compressed;
142 float total_out_uncompressed;
143 float total_in_uncompressed;
147 ModuleZLib(InspIRCd* Me)
150 ServerInstance->PublishInterface("InspSocketHook", this);
152 total_out_compressed = total_in_compressed = 0;
153 total_out_uncompressed = total_out_uncompressed = 0;
156 virtual ~ModuleZLib()
160 virtual Version GetVersion()
162 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
165 void Implements(char* List)
167 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
168 List[I_OnStats] = List[I_OnRequest] = 1;
171 virtual char* OnRequest(Request* request)
173 ISHRequest* ISR = (ISHRequest*)request;
174 if (strcmp("IS_NAME", request->GetId()) == 0)
178 else if (strcmp("IS_HOOK", request->GetId()) == 0)
183 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
185 catch (ModuleException& e)
191 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
193 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
195 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
199 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
206 virtual int OnStats(char symbol, userrec* user, string_list &results)
210 std::string sn = ServerInstance->Config->ServerName;
212 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
213 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
215 float total_compressed = total_in_compressed + total_out_compressed;
216 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
218 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
220 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
222 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
223 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
224 sprintf(combined_ratio, "%3.2f%%", total_r);
226 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
227 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
228 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
229 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
230 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
231 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
232 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
239 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
241 izip_session* session = &sessions[fd];
243 /* allocate deflate state */
245 session->status = IZIP_OPEN;
247 session->inbuf = new CountedBuffer();
248 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
250 session->c_stream.zalloc = (alloc_func)0;
251 session->c_stream.zfree = (free_func)0;
252 session->c_stream.opaque = (voidpf)0;
254 session->d_stream.zalloc = (alloc_func)0;
255 session->d_stream.zfree = (free_func)0;
256 session->d_stream.opaque = (voidpf)0;
259 virtual void OnRawSocketConnect(int fd)
261 OnRawSocketAccept(fd, "", 0);
264 virtual void OnRawSocketClose(int fd)
266 CloseSession(&sessions[fd]);
269 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
271 izip_session* session = &sessions[fd];
273 if (session->status == IZIP_CLOSED)
276 unsigned char compr[CHUNK + 1];
278 readresult = read(fd, compr, CHUNK);
282 session->inbuf->AddData(compr, readresult);
286 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
288 unsigned char localbuf[count + 1];
290 session->d_stream.next_in = (Bytef*)compr;
291 session->d_stream.avail_in = 0;
292 session->d_stream.next_out = (Bytef*)localbuf;
293 if (inflateInit(&session->d_stream) != Z_OK)
296 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
298 session->d_stream.avail_in = session->d_stream.avail_out = 1;
299 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
303 inflateEnd(&session->d_stream);
305 localbuf[session->d_stream.total_out] = 0;
306 str_out.append((const char*)localbuf);
307 total_in_compressed += readresult;
308 readresult = session->d_stream.total_out;
309 total_in_uncompressed += session->d_stream.total_out;
312 memcpy(buffer, str_out.data(), str_out.length() > count ? count : str_out.length());
313 readresult = str_out.length();
315 return (readresult > 0);
318 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
320 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
322 izip_session* session = &sessions[fd];
327 ServerInstance->Log(DEBUG,"Nothing to do!");
331 if(session->status != IZIP_OPEN)
333 CloseSession(session);
337 unsigned char compr[CHUNK];
339 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
341 ServerInstance->Log(DEBUG,"Deflate init failed");
344 session->c_stream.next_in = (Bytef*)buffer;
345 session->c_stream.next_out = compr+4;
347 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
349 session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
350 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
352 ServerInstance->Log(DEBUG,"Couldnt deflate!");
353 CloseSession(session);
357 /* Finish the stream, still forcing small buffers: */
360 session->c_stream.avail_out = 1;
361 if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
365 deflateEnd(&session->c_stream);
367 total_out_uncompressed += ocount;
368 total_out_compressed += session->c_stream.total_out;
370 int x = htonl(session->c_stream.total_out);
371 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
372 * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
373 * assembling the frame size into the same packet as the compressed frame.
375 memcpy(compr, &x, sizeof(x));
377 const char* string_likes_signed_chars = (const char*)compr;
378 session->outbuf.append(string_likes_signed_chars, session->c_stream.total_out+4);
380 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
383 session->outbuf = session->outbuf.substr(ret);
387 return errno == EAGAIN;
392 ServerInstance->Log(DEBUG,"Sending frame of size %d", ntohl(x));
394 /* ALL LIES the lot of it, we havent really written
395 * this amount, but the layer above doesnt need to know.
400 void CloseSession(izip_session* session)
402 if (session->status = IZIP_OPEN)
404 session->status = IZIP_CLOSED;
405 session->outbuf = "";
406 delete session->inbuf;
412 class ModuleZLibFactory : public ModuleFactory
423 virtual Module * CreateModule(InspIRCd* Me)
425 return new ModuleZLib(Me);
430 extern "C" void * init_module( void )
432 return new ModuleZLibFactory;