6 #include "inspircd_config.h"
7 #include "configreader.h"
16 #include "transport.h"
18 /* $ModDesc: Provides zlib link support for servers */
19 /* $LinkerFlags: -lz */
20 /* $ModDep: transport.h */
23 * Compressed data is transmitted across the link in the following format:
26 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
28 * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
30 * Where: n is the size of a frame, in network byte order, 4 bytes.
31 * Z0 through Zn are Zlib compressed data, n bytes in length.
33 * If the module fails to read the entire frame, then it will buffer
34 * the portion of the last frame it received, then attempt to read
35 * the next part of the frame next time a write notification arrives.
37 * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
38 * a flush after each frame. A frame may contain multiple lines
39 * and should be treated as raw binary data.
43 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
45 const unsigned int CHUNK = 128 * 1024;
47 class CountedBuffer : public classbase
49 std::deque<unsigned char> buffer; /* Current buffer contents */
50 unsigned int amount_expected; /* Amount of data expected */
57 void AddData(unsigned char* data, int data_length)
59 for (int i = 0; i < data_length; i++)
60 buffer.push_back(data[i]);
62 this->NextFrameSize();
67 if ((!amount_expected) && (buffer.size() >= 4))
69 /* We have enough to read an int */
71 for (int i = 0; i < 4; i++)
73 sz[i] = buffer.front();
77 amount_expected = ntohl(*size);
81 int GetFrame(unsigned char* frame, int maxsize)
85 /* We know how much we're expecting...
86 * Do we have enough yet?
88 if (buffer.size() >= amount_expected)
91 for (unsigned int i = 0; i < amount_expected; i++, j++)
93 frame[i] = buffer.front();
103 /* Not enough for a frame yet, COME AGAIN! */
108 /** Represents an ZIP user's extra data
110 class izip_session : public classbase
113 z_stream c_stream; /* compression stream */
114 z_stream d_stream; /* decompress stream */
117 CountedBuffer* inbuf;
121 class ModuleZLib : public Module
123 izip_session sessions[MAX_DESCRIPTORS];
124 float total_out_compressed;
125 float total_in_compressed;
126 float total_out_uncompressed;
127 float total_in_uncompressed;
131 ModuleZLib(InspIRCd* Me)
134 ServerInstance->PublishInterface("InspSocketHook", this);
136 total_out_compressed = total_in_compressed = 0;
137 total_out_uncompressed = total_out_uncompressed = 0;
140 virtual ~ModuleZLib()
144 virtual Version GetVersion()
146 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
149 void Implements(char* List)
151 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
152 List[I_OnStats] = List[I_OnRequest] = 1;
155 virtual char* OnRequest(Request* request)
157 ISHRequest* ISR = (ISHRequest*)request;
158 if (strcmp("IS_NAME", request->GetId()) == 0)
162 else if (strcmp("IS_HOOK", request->GetId()) == 0)
167 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
169 catch (ModuleException& e)
175 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
177 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
179 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
183 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
190 virtual int OnStats(char symbol, userrec* user, string_list &results)
194 std::string sn = ServerInstance->Config->ServerName;
196 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
197 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
199 float total_compressed = total_in_compressed + total_out_compressed;
200 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
202 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
204 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
206 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
207 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
208 sprintf(combined_ratio, "%3.2f%%", total_r);
210 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
211 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
212 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
213 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
214 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
215 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
216 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
223 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
225 izip_session* session = &sessions[fd];
227 /* allocate deflate state */
229 session->status = IZIP_OPEN;
231 session->inbuf = new CountedBuffer();
232 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
234 session->c_stream.zalloc = (alloc_func)0;
235 session->c_stream.zfree = (free_func)0;
236 session->c_stream.opaque = (voidpf)0;
238 session->d_stream.zalloc = (alloc_func)0;
239 session->d_stream.zfree = (free_func)0;
240 session->d_stream.opaque = (voidpf)0;
243 virtual void OnRawSocketConnect(int fd)
245 OnRawSocketAccept(fd, "", 0);
248 virtual void OnRawSocketClose(int fd)
250 CloseSession(&sessions[fd]);
253 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
255 izip_session* session = &sessions[fd];
257 if (session->status == IZIP_CLOSED)
260 unsigned char compr[CHUNK + 1];
262 readresult = read(fd, compr, CHUNK);
266 session->inbuf->AddData(compr, readresult);
270 while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)
272 unsigned char localbuf[count + 1];
274 session->d_stream.next_in = (Bytef*)compr;
275 session->d_stream.avail_in = 0;
276 session->d_stream.next_out = (Bytef*)localbuf;
277 if (inflateInit(&session->d_stream) != Z_OK)
280 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
282 session->d_stream.avail_in = session->d_stream.avail_out = 1;
283 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
287 inflateEnd(&session->d_stream);
289 localbuf[session->d_stream.total_out] = 0;
290 str_out.append((const char*)localbuf);
291 total_in_compressed += readresult;
292 readresult = session->d_stream.total_out;
293 total_in_uncompressed += session->d_stream.total_out;
296 memcpy(buffer, str_out.data(), str_out.length() > count ? count : str_out.length());
297 readresult = str_out.length();
299 return (readresult > 0);
302 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
304 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
306 izip_session* session = &sessions[fd];
311 ServerInstance->Log(DEBUG,"Nothing to do!");
315 if(session->status != IZIP_OPEN)
317 CloseSession(session);
321 unsigned char compr[CHUNK];
323 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
325 ServerInstance->Log(DEBUG,"Deflate init failed");
328 session->c_stream.next_in = (Bytef*)buffer;
329 session->c_stream.next_out = compr+4;
331 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
333 session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
334 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
336 ServerInstance->Log(DEBUG,"Couldnt deflate!");
337 CloseSession(session);
341 /* Finish the stream, still forcing small buffers: */
344 session->c_stream.avail_out = 1;
345 if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
349 deflateEnd(&session->c_stream);
351 total_out_uncompressed += ocount;
352 total_out_compressed += session->c_stream.total_out;
354 int x = htonl(session->c_stream.total_out);
355 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
356 * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
357 * assembling the frame size into the same packet as the compressed frame.
359 memcpy(compr, &x, sizeof(x));
361 const char* string_likes_signed_chars = (const char*)compr;
362 session->outbuf.append(string_likes_signed_chars, session->c_stream.total_out+4);
364 int ret = write(fd, session->outbuf.data(), session->outbuf.length());
366 ServerInstance->Log(DEBUG,"Sending frame of size %d", ntohl(x));
368 session->outbuf = session->outbuf.substr(ret);
373 void CloseSession(izip_session* session)
375 if (session->status = IZIP_OPEN)
377 session->status = IZIP_CLOSED;
378 session->outbuf = "";
379 delete session->inbuf;
385 class ModuleZLibFactory : public ModuleFactory
396 virtual Module * CreateModule(InspIRCd* Me)
398 return new ModuleZLib(Me);
403 extern "C" void * init_module( void )
405 return new ModuleZLibFactory;