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.
45 enum izip_status { IZIP_OPEN, IZIP_CLOSED };
47 const unsigned int CHUNK = 128 * 1024;
49 class CountedBuffer : public classbase
51 int bufptr; /* Current tail location */
52 unsigned char* buffer; /* Current buffer contents */
53 int bufsz; /* Current buffer size */
54 int amount_expected; /* Amount of data expected */
55 int amount_read; /* Amount of data read so far */
60 buffer = new unsigned char[bufsz + 1];
71 void AddData(unsigned char* data, int data_length)
73 SI->Log(DEBUG,"AddData, %d bytes to add", data_length);
74 if ((data_length + bufptr) > bufsz)
76 SI->Log(DEBUG,"Need to extend buffer to %d, is now %d", data_length + bufptr, bufsz);
77 /* Buffer is too small, enlarge it and copy contents */
78 int old_bufsz = bufsz;
79 unsigned char* temp = buffer;
82 buffer = new unsigned char[bufsz + 1];
84 memcpy(buffer, temp, old_bufsz);
89 SI->Log(DEBUG,"Copy data in at pos %d", bufptr);
91 memcpy(buffer + bufptr, data, data_length);
92 bufptr += data_length;
93 amount_read += data_length;
95 SI->Log(DEBUG,"Amount read is now %d, bufptr is now %d", amount_read, bufptr);
97 if ((!amount_expected) && (amount_read >= 4))
99 SI->Log(DEBUG,"We dont yet have an expected amount");
100 /* We have enough to read an int */
101 int* size = (int*)buffer;
102 amount_expected = ntohl(*size);
103 SI->Log(DEBUG,"Expected amount is %d", amount_expected);
107 int GetFrame(unsigned char* frame, int maxsize)
111 SI->Log(DEBUG,"Were expecting a frame of size %d", amount_expected);
112 /* We know how much we're expecting...
113 * Do we have enough yet?
115 if ((amount_read - 4) >= amount_expected)
117 SI->Log(DEBUG,"We have enough for the frame (have %d)", (amount_read - 4));
118 int amt_ex = amount_expected;
119 /* Yes, we have enough now */
120 memcpy(frame, buffer + 4, amount_expected > maxsize ? maxsize : amount_expected);
122 return (amt_ex > maxsize) ? maxsize : amt_ex;
125 /* Not enough for a frame yet, COME AGAIN! */
129 void RemoveFirstFrame()
131 SI->Log(DEBUG,"Removing first frame from buffer sized %d", amount_expected);
132 unsigned char* temp = buffer;
134 bufsz -= (amount_expected + 4);
135 buffer = new unsigned char[bufsz + 1];
137 SI->Log(DEBUG,"Shrunk buffer to %d", bufsz);
139 memcpy(buffer, temp + amount_expected + 4, bufsz);
141 amount_read -= (amount_expected + 4);
142 SI->Log(DEBUG,"Amount read now %d", amount_read);
144 if (amount_read >= 4)
146 /* We have enough to read an int */
147 int* size = (int*)buffer;
148 amount_expected = ntohl(*size);
153 SI->Log(DEBUG,"Amount expected now %d", amount_expected);
161 /** Represents an ZIP user's extra data
163 class izip_session : public classbase
166 z_stream c_stream; /* compression stream */
167 z_stream d_stream; /* decompress stream */
170 CountedBuffer* inbuf;
173 class ModuleZLib : public Module
175 izip_session sessions[MAX_DESCRIPTORS];
176 float total_out_compressed;
177 float total_in_compressed;
178 float total_out_uncompressed;
179 float total_in_uncompressed;
183 ModuleZLib(InspIRCd* Me)
186 ServerInstance->PublishInterface("InspSocketHook", this);
188 total_out_compressed = total_in_compressed = 0;
189 total_out_uncompressed = total_out_uncompressed = 0;
194 virtual ~ModuleZLib()
198 virtual Version GetVersion()
200 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
203 void Implements(char* List)
205 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;
206 List[I_OnStats] = List[I_OnRequest] = 1;
209 virtual char* OnRequest(Request* request)
211 ISHRequest* ISR = (ISHRequest*)request;
212 if (strcmp("IS_NAME", request->GetId()) == 0)
216 else if (strcmp("IS_HOOK", request->GetId()) == 0)
221 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
223 catch (ModuleException& e)
229 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
231 return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
233 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
237 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
244 virtual int OnStats(char symbol, userrec* user, string_list &results)
248 std::string sn = ServerInstance->Config->ServerName;
250 float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);
251 float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);
253 float total_compressed = total_in_compressed + total_out_compressed;
254 float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
256 float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);
258 char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
260 sprintf(outbound_ratio, "%3.2f%%", outbound_r);
261 sprintf(inbound_ratio, "%3.2f%%", inbound_r);
262 sprintf(combined_ratio, "%3.2f%%", total_r);
264 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed = "+ConvToStr(total_out_compressed));
265 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed = "+ConvToStr(total_in_compressed));
266 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
267 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed = "+ConvToStr(total_in_uncompressed));
268 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio = "+outbound_ratio);
269 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio = "+inbound_ratio);
270 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio = "+combined_ratio);
277 virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
279 izip_session* session = &sessions[fd];
281 /* allocate deflate state */
283 session->status = IZIP_OPEN;
285 session->inbuf = new CountedBuffer();
286 ServerInstance->Log(DEBUG,"session->inbuf ALLOC = %d, %08x", fd, session->inbuf);
288 session->c_stream.zalloc = (alloc_func)0;
289 session->c_stream.zfree = (free_func)0;
290 session->c_stream.opaque = (voidpf)0;
292 session->d_stream.zalloc = (alloc_func)0;
293 session->d_stream.zfree = (free_func)0;
294 session->d_stream.opaque = (voidpf)0;
297 virtual void OnRawSocketConnect(int fd)
299 OnRawSocketAccept(fd, "", 0);
302 virtual void OnRawSocketClose(int fd)
304 CloseSession(&sessions[fd]);
307 virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
309 izip_session* session = &sessions[fd];
311 if (session->status == IZIP_CLOSED)
314 unsigned char compr[CHUNK + 1];
315 unsigned int total_decomp = 0;
317 readresult = read(fd, compr, CHUNK);
321 session->inbuf->AddData(compr, readresult);
323 int size = session->inbuf->GetFrame(compr, CHUNK);
324 while ((size) && (total_decomp < count))
327 session->d_stream.next_in = (Bytef*)compr;
328 session->d_stream.avail_in = 0;
329 session->d_stream.next_out = (Bytef*)(buffer + total_decomp);
330 if (inflateInit(&session->d_stream) != Z_OK)
333 while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))
335 session->d_stream.avail_in = session->d_stream.avail_out = 1;
336 if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)
340 inflateEnd(&session->d_stream);
342 total_in_compressed += readresult;
343 readresult = session->d_stream.total_out;
344 total_in_uncompressed += session->d_stream.total_out;
346 total_decomp += session->d_stream.total_out;
348 ServerInstance->Log(DEBUG,"Decompressed %d bytes, total_decomp=%d: '%s'", session->d_stream.total_out, total_decomp, buffer);
350 size = session->inbuf->GetFrame(compr, CHUNK);
353 buffer[total_decomp] = 0;
355 ServerInstance->Log(DEBUG,"Complete buffer: '%s' size=%d", buffer, total_decomp);
357 return (readresult > 0);
360 virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
362 ServerInstance->Log(DEBUG,"Compressing %d bytes", count);
364 izip_session* session = &sessions[fd];
369 ServerInstance->Log(DEBUG,"Nothing to do!");
373 if(session->status != IZIP_OPEN)
375 CloseSession(session);
379 unsigned char compr[CHUNK];
381 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
383 ServerInstance->Log(DEBUG,"Deflate init failed");
386 session->c_stream.next_in = (Bytef*)buffer;
387 session->c_stream.next_out = compr+4;
389 while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))
391 session->c_stream.avail_in = session->c_stream.avail_out = 1; /* force small buffers */
392 if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)
394 ServerInstance->Log(DEBUG,"Couldnt deflate!");
395 CloseSession(session);
399 /* Finish the stream, still forcing small buffers: */
402 session->c_stream.avail_out = 1;
403 if (deflate(&session->c_stream, Z_FINISH) == Z_STREAM_END)
407 deflateEnd(&session->c_stream);
409 total_out_uncompressed += ocount;
410 total_out_compressed += session->c_stream.total_out;
412 int x = htonl(session->c_stream.total_out);
413 /** XXX: We memcpy it onto the start of the buffer like this to save ourselves a write().
414 * A memcpy of 4 or so bytes is less expensive and gives the tcp stack more chance of
415 * assembling the frame size into the same packet as the compressed frame.
417 memcpy(compr, &x, sizeof(x));
418 write(fd, compr, session->c_stream.total_out+4);
420 ServerInstance->Log(DEBUG,"Sending frame of size %d", x);
425 void CloseSession(izip_session* session)
427 if (session->status = IZIP_OPEN)
429 session->status = IZIP_CLOSED;
430 delete session->inbuf;
436 class ModuleZLibFactory : public ModuleFactory
447 virtual Module * CreateModule(InspIRCd* Me)
449 return new ModuleZLib(Me);
454 extern "C" void * init_module( void )
456 return new ModuleZLibFactory;