]> git.netwichtig.de Git - user/henk/code/inspircd.git/blobdiff - src/modules/extra/m_ziplink.cpp
Remove InspIRCd* parameters and fields
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
index 2a127258dc883a89c503df3b20824b68dafc2986..976a27b5c7293bec55c4a336b428aaec1f3d989d 100644 (file)
@@ -1 +1,412 @@
-/*       +------------------------------------+\r *       | Inspire Internet Relay Chat Daemon |\r *       +------------------------------------+\r *\r *  InspIRCd: (C) 2002-2007 InspIRCd Development Team\r * See: http://www.inspircd.org/wiki/index.php/Credits\r *\r * This program is free but copyrighted software; see\r *            the file COPYING for details.\r *\r * ---------------------------------------------------\r */\r\r#include "inspircd.h"\r#include <zlib.h>\r#include "users.h"\r#include "channels.h"\r#include "modules.h"\r#include "socket.h"\r#include "hashcomp.h"\r#include "transport.h"\r\r/* $ModDesc: Provides zlib link support for servers */\r/* $LinkerFlags: -lz */\r/* $ModDep: transport.h */\r\r/*\r * Compressed data is transmitted across the link in the following format:\r *\r *   0   1   2   3   4 ... n\r * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\r * |       n       |              Z0 -> Zn                         |\r * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\r *\r * Where: n is the size of a frame, in network byte order, 4 bytes.\r * Z0 through Zn are Zlib compressed data, n bytes in length.\r *\r * If the module fails to read the entire frame, then it will buffer\r * the portion of the last frame it received, then attempt to read\r * the next part of the frame next time a write notification arrives.\r *\r * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with\r * a flush after each frame. A frame may contain multiple lines\r * and should be treated as raw binary data.\r *\r */\r\r/* Status of a connection */\renum izip_status { IZIP_OPEN, IZIP_CLOSED };\r\r/* Maximum transfer size per read operation */\rconst unsigned int CHUNK = 128 * 1024;\r\r/* This class manages a compressed chunk of data preceeded by\r * a length count.\r *\r * It can handle having multiple chunks of data in the buffer\r * at any time.\r */\rclass CountedBuffer : public classbase\r{\r  std::string buffer;             /* Current buffer contents */\r  unsigned int amount_expected;   /* Amount of data expected */\r public:\r CountedBuffer()\r        {\r              amount_expected = 0;\r   }\r\r     /** Adds arbitrary compressed data to the buffer.\r       * - Binsry safe, of course.\r    */\r    void AddData(unsigned char* data, int data_length)\r     {\r              buffer.append((const char*)data, data_length);\r         this->NextFrameSize();\r }\r\r     /** Works out the size of the next compressed frame\r     */\r    void NextFrameSize()\r   {\r              if ((!amount_expected) && (buffer.length() >= 4))\r              {\r                      /* We have enough to read an int -\r                      * Yes, this is safe, but its ugly. Give me\r                     * a nicer way to read 4 bytes from a binary\r                    * stream, and push them into a 32 bit int,\r                     * and i'll consider replacing this.\r                    */\r                    amount_expected = ntohl((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0]);\r                 buffer = buffer.substr(4);\r             }\r      }\r\r     /** Gets the next frame and returns its size, or returns\r        * zero if there isnt one available yet.\r        * A frame can contain multiple plaintext lines.\r        * - Binary safe.\r       */\r    int GetFrame(unsigned char* frame, int maxsize)\r        {\r              if (amount_expected)\r           {\r                      /* We know how much we're expecting...\r                  * Do we have enough yet?\r                       */\r                    if (buffer.length() >= amount_expected)\r                        {\r                              int j = 0;\r                             for (unsigned int i = 0; i < amount_expected; i++, j++)\r                                        frame[i] = buffer[i];\r\r                         buffer = buffer.substr(j);\r                             amount_expected = 0;\r                           NextFrameSize();\r                               return j;\r                      }\r              }\r              /* Not enough for a frame yet, COME AGAIN! */\r          return 0;\r      }\r};\r\r/** Represents an zipped connections extra data\r */\rclass izip_session : public classbase\r{\r public:\r     z_stream c_stream;      /* compression stream */\r       z_stream d_stream;      /* decompress stream */\r        izip_status status;     /* Connection status */\r        int fd;                 /* File descriptor */\r  CountedBuffer* inbuf;   /* Holds input buffer */\r       std::string outbuf;     /* Holds output buffer */\r};\r\rclass ModuleZLib : public Module\r{\r       izip_session sessions[MAX_DESCRIPTORS];\r\r       /* Used for stats z extensions */\r      float total_out_compressed;\r    float total_in_compressed;\r     float total_out_uncompressed;\r  float total_in_uncompressed;\r   \r public:\r      \r       ModuleZLib(InspIRCd* Me)\r               : Module::Module(Me)\r   {\r              ServerInstance->PublishInterface("InspSocketHook", this);\r\r             total_out_compressed = total_in_compressed = 0;\r                total_out_uncompressed = total_out_uncompressed = 0;\r   }\r\r     virtual ~ModuleZLib()\r  {\r              ServerInstance->UnpublishInterface("InspSocketHook", this);\r    }\r\r     virtual Version GetVersion()\r   {\r              return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);\r    }\r\r     void Implements(char* List)\r    {\r              List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = 1;\r            List[I_OnStats] = List[I_OnRequest] = 1;\r       }\r\r     /* Handle InspSocketHook API requests */\r       virtual char* OnRequest(Request* request)\r      {\r              ISHRequest* ISR = (ISHRequest*)request;\r                if (strcmp("IS_NAME", request->GetId()) == 0)\r          {\r                      /* Return name */\r                      return "zip";\r          }\r              else if (strcmp("IS_HOOK", request->GetId()) == 0)\r             {\r                      /* Attach to an inspsocket */\r                  char* ret = "OK";\r                      try\r                    {\r                              ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;\r                   }\r                      catch (ModuleException& e)\r                     {\r                              return NULL;\r                   }\r                      return ret;\r            }\r              else if (strcmp("IS_UNHOOK", request->GetId()) == 0)\r           {\r                      /* Detatch from an inspsocket */\r                       return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;\r         }\r              else if (strcmp("IS_HSDONE", request->GetId()) == 0)\r           {\r                      /* Check for completion of handshake\r                    * (actually, this module doesnt handshake)\r                     */\r                    return "OK";\r           }\r              else if (strcmp("IS_ATTACH", request->GetId()) == 0)\r           {\r                      /* Attach certificate data to the inspsocket\r                    * (this module doesnt do that, either)\r                         */\r                    return NULL;\r           }\r              return NULL;\r   }\r\r     /* Handle stats z (misc stats) */\r      virtual int OnStats(char symbol, userrec* user, string_list &results)\r  {\r              if (symbol == 'z')\r             {\r                      std::string sn = ServerInstance->Config->ServerName;\r\r                  /* Yeah yeah, i know, floats are ew.\r                    * We used them here because we'd be casting to float anyway to do this maths,\r                  * and also only floating point numbers can deal with the pretty large numbers\r                  * involved in the total throughput of a server over a large period of time.\r                    * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats\r                      * can still hold more.\r                         */\r                    float outbound_r = 100 - ((total_out_compressed / (total_out_uncompressed + 0.001)) * 100);\r                    float inbound_r = 100 - ((total_in_compressed / (total_in_uncompressed + 0.001)) * 100);\r\r                      float total_compressed = total_in_compressed + total_out_compressed;\r                   float total_uncompressed = total_in_uncompressed + total_out_uncompressed;\r\r                    float total_r = 100 - ((total_compressed / (total_uncompressed + 0.001)) * 100);\r\r                      char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];\r\r                   sprintf(outbound_ratio, "%3.2f%%", outbound_r);\r                        sprintf(inbound_ratio, "%3.2f%%", inbound_r);\r                  sprintf(combined_ratio, "%3.2f%%", total_r);\r\r                  results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));\r                        results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));\r                 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));\r                      results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));\r                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_ratio        = "+outbound_ratio);\r                 results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_ratio         = "+inbound_ratio);\r                  results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS combined_ratio        = "+combined_ratio);\r                 return 0;\r              }\r\r             return 0;\r      }\r\r     virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)\r   {\r              izip_session* session = &sessions[fd];\r \r               /* allocate state and buffers */\r               session->fd = fd;\r              session->status = IZIP_OPEN;\r           session->inbuf = new CountedBuffer();\r\r         session->c_stream.zalloc = (alloc_func)0;\r              session->c_stream.zfree = (free_func)0;\r                session->c_stream.opaque = (voidpf)0;\r\r         session->d_stream.zalloc = (alloc_func)0;\r              session->d_stream.zfree = (free_func)0;\r                session->d_stream.opaque = (voidpf)0;\r  }\r\r     virtual void OnRawSocketConnect(int fd)\r        {\r              /* Nothing special needs doing here compared to accept() */\r            OnRawSocketAccept(fd, "", 0);\r  }\r\r     virtual void OnRawSocketClose(int fd)\r  {\r              CloseSession(&sessions[fd]);\r   }\r\r     virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)\r {\r              /* Find the sockets session */\r         izip_session* session = &sessions[fd];\r\r                if (session->status == IZIP_CLOSED)\r                    return 0;\r\r             unsigned char compr[CHUNK + 4];\r                unsigned int offset = 0;\r               unsigned int total_size = 0;\r\r          /* Read CHUNK bytes at a time to the buffer (usually 128k) */\r          readresult = read(fd, compr, CHUNK);\r\r          /* Did we get anything? */\r             if (readresult > 0)\r            {\r                      /* Add it to the frame queue */\r                        session->inbuf->AddData(compr, readresult);\r                    total_in_compressed += readresult;\r     \r                       /* Parse all completed frames */\r                       int size = 0;\r                  while ((size = session->inbuf->GetFrame(compr, CHUNK)) != 0)\r                   {\r                              session->d_stream.next_in  = (Bytef*)compr;\r                            session->d_stream.avail_in = 0;\r                                session->d_stream.next_out = (Bytef*)(buffer + offset);\r\r                               /* If we cant call this, well, we're boned. */\r                         if (inflateInit(&session->d_stream) != Z_OK)\r                                   return 0;\r      \r                               while ((session->d_stream.total_out < count) && (session->d_stream.total_in < (unsigned int)size))\r                             {\r                                      session->d_stream.avail_in = session->d_stream.avail_out = 1;\r                                  if (inflate(&session->d_stream, Z_NO_FLUSH) == Z_STREAM_END)\r                                           break;\r                         }\r      \r                               /* Stick a fork in me, i'm done */\r                             inflateEnd(&session->d_stream);\r\r                               /* Update counters and offsets */\r                              total_size += session->d_stream.total_out;\r                             total_in_uncompressed += session->d_stream.total_out;\r                          offset += session->d_stream.total_out;\r                 }\r\r                     /* Null-terminate the buffer -- this doesnt harm binary data */\r                        buffer[total_size] = 0;\r\r                       /* Set the read size to the correct total size */\r                      readresult = total_size;\r\r              }\r              return (readresult > 0);\r       }\r\r     virtual int OnRawSocketWrite(int fd, const char* buffer, int count)\r    {\r              izip_session* session = &sessions[fd];\r         int ocount = count;\r\r           if (!count)     /* Nothing to do! */\r                   return 0;\r\r             if(session->status != IZIP_OPEN)\r               {\r                      /* Seriously, wtf? */\r                  CloseSession(session);\r                 return 0;\r              }\r\r             unsigned char compr[CHUNK + 4];\r\r               /* Gentlemen, start your engines! */\r           if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)\r               {\r                      CloseSession(session);\r                 return 0;\r              }\r\r             /* Set buffer sizes (we reserve 4 bytes at the start of the\r             * buffer for the length counters)\r              */\r            session->c_stream.next_in  = (Bytef*)buffer;\r           session->c_stream.next_out = compr + 4;\r\r               /* Compress the text */\r                while ((session->c_stream.total_in < (unsigned int)count) && (session->c_stream.total_out < CHUNK))\r            {\r                      session->c_stream.avail_in = session->c_stream.avail_out = 1;\r                  if (deflate(&session->c_stream, Z_NO_FLUSH) != Z_OK)\r                   {\r                              CloseSession(session);\r                         return 0;\r                      }\r              }\r              /* Finish the stream */\r                for (session->c_stream.avail_out = 1; deflate(&session->c_stream, Z_FINISH) != Z_STREAM_END; session->c_stream.avail_out = 1);\r         deflateEnd(&session->c_stream);\r\r               total_out_uncompressed += ocount;\r              total_out_compressed += session->c_stream.total_out;\r\r          /** Assemble the frame length onto the frame, in network byte order */\r         compr[0] = (session->c_stream.total_out >> 24);\r                compr[1] = (session->c_stream.total_out >> 16);\r                compr[2] = (session->c_stream.total_out >> 8);\r         compr[3] = (session->c_stream.total_out & 0xFF);\r\r              /* Add compressed data plus leading length to the output buffer -\r               * Note, we may have incomplete half-sent frames in here.\r               */\r            session->outbuf.append((const char*)compr, session->c_stream.total_out + 4);\r\r          /* Lets see how much we can send out */\r                int ret = write(fd, session->outbuf.data(), session->outbuf.length());\r\r                /* Check for errors, and advance the buffer if any was sent */\r         if (ret > 0)\r                   session->outbuf = session->outbuf.substr(ret);\r         else if (ret < 1)\r              {\r                      if (ret == -1)\r                 {\r                              if (errno == EAGAIN)\r                                   return 0;\r                              else\r                           {\r                                      session->outbuf.clear();\r                                       return 0;\r                              }\r                      }\r                      else\r                   {\r                              session->outbuf.clear();\r                               return 0;\r                      }\r              }\r\r             /* ALL LIES the lot of it, we havent really written\r             * this amount, but the layer above doesnt need to know.\r                */\r            return ocount;\r }\r      \r       void CloseSession(izip_session* session)\r       {\r              if (session->status == IZIP_OPEN)\r              {\r                      session->status = IZIP_CLOSED;\r                 session->outbuf.clear();\r                       delete session->inbuf;\r         }\r      }\r\r};\r\rMODULE_INIT(ModuleZLib);\r\r
\ No newline at end of file
+/*       +------------------------------------+
+ *       | Inspire Internet Relay Chat Daemon |
+ *       +------------------------------------+
+ *
+ *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
+ * See: http://wiki.inspircd.org/Credits
+ *
+ * This program is free but copyrighted software; see
+ *            the file COPYING for details.
+ *
+ * ---------------------------------------------------
+ */
+
+#include "inspircd.h"
+#include <zlib.h>
+#include "transport.h"
+#include <iostream>
+
+/* $ModDesc: Provides zlib link support for servers */
+/* $LinkerFlags: -lz */
+/* $ModDep: transport.h */
+
+/*
+ * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
+ * a flush after each chunk. A frame may contain multiple lines
+ * and should be treated as raw binary data.
+ */
+
+/* Status of a connection */
+enum izip_status { IZIP_CLOSED = 0, IZIP_OPEN };
+
+/** Represents an zipped connections extra data
+ */
+class izip_session : public classbase
+{
+ public:
+       z_stream c_stream;      /* compression stream */
+       z_stream d_stream;      /* uncompress stream */
+       izip_status status;     /* Connection status */
+       std::string outbuf;     /* Holds output buffer (compressed) */
+       std::string inbuf;      /* Holds input buffer (compressed) */
+};
+
+class ModuleZLib : public Module
+{
+       izip_session* sessions;
+
+       /* Used for stats z extensions */
+       float total_out_compressed;
+       float total_in_compressed;
+       float total_out_uncompressed;
+       float total_in_uncompressed;
+
+       /* Used for reading data from the wire and compressing data to. */
+       char *net_buffer;
+       unsigned int net_buffer_size;
+ public:
+
+       ModuleZLib()
+                       {
+               ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
+
+               sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
+               for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
+                       sessions[i].status = IZIP_CLOSED;
+
+               total_out_compressed = total_in_compressed = 0;
+               total_out_uncompressed = total_in_uncompressed = 0;
+               Implementation eventlist[] = { I_OnStats, I_OnRequest };
+               ServerInstance->Modules->Attach(eventlist, this, 2);
+
+               // Allocate a buffer which is used for reading and writing data
+               net_buffer_size = ServerInstance->Config->NetBufferSize;
+               net_buffer = new char[net_buffer_size];
+       }
+
+       ~ModuleZLib()
+       {
+               ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
+               delete[] sessions;
+               delete[] net_buffer;
+       }
+
+       Version GetVersion()
+       {
+               return Version("Provides zlib link support for servers", VF_VENDOR, API_VERSION);
+       }
+
+
+       /* Handle BufferedSocketHook API requests */
+       const char* OnRequest(Request* request)
+       {
+               ISHRequest* ISR = (ISHRequest*)request;
+               if (strcmp("IS_NAME", request->GetId()) == 0)
+               {
+                       /* Return name */
+                       return "zip";
+               }
+               else if (strcmp("IS_HOOK", request->GetId()) == 0)
+               {
+                       ISR->Sock->AddIOHook(this);
+                       return "OK";
+               }
+               else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
+               {
+                       ISR->Sock->DelIOHook();
+                       return "OK";
+               }
+               else if (strcmp("IS_HSDONE", request->GetId()) == 0)
+               {
+                       /* Check for completion of handshake
+                        * (actually, this module doesnt handshake)
+                        */
+                       return "OK";
+               }
+               else if (strcmp("IS_ATTACH", request->GetId()) == 0)
+               {
+                       /* Attach certificate data to the inspsocket
+                        * (this module doesnt do that, either)
+                        */
+                       return NULL;
+               }
+               return NULL;
+       }
+
+       /* Handle stats z (misc stats) */
+       ModResult OnStats(char symbol, User* user, string_list &results)
+       {
+               if (symbol == 'z')
+               {
+                       std::string sn = ServerInstance->Config->ServerName;
+
+                       /* Yeah yeah, i know, floats are ew.
+                        * We used them here because we'd be casting to float anyway to do this maths,
+                        * and also only floating point numbers can deal with the pretty large numbers
+                        * involved in the total throughput of a server over a large period of time.
+                        * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
+                        * can still hold more.
+                        */
+                       float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
+                       float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
+
+                       float total_compressed = total_in_compressed + total_out_compressed;
+                       float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
+
+                       float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
+
+                       char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
+
+                       sprintf(outbound_ratio, "%3.2f%%", outbound_r);
+                       sprintf(inbound_ratio, "%3.2f%%", inbound_r);
+                       sprintf(combined_ratio, "%3.2f%%", total_r);
+
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_original_outbound_traffic        = "+outbound_ratio);
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_orignal_inbound_traffic         = "+inbound_ratio);
+                       results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS total_size_of_original_traffic        = "+combined_ratio);
+                       return MOD_RES_PASSTHRU;
+               }
+
+               return MOD_RES_PASSTHRU;
+       }
+
+       void OnStreamSocketConnect(StreamSocket* user)
+       {
+               OnStreamSocketAccept(user, 0, 0);
+       }
+
+       void OnRawSocketAccept(StreamSocket* user, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*)
+       {
+               int fd = user->GetFd();
+
+               izip_session* session = &sessions[fd];
+
+               /* Just in case... */
+               session->outbuf.clear();
+
+               session->c_stream.zalloc = (alloc_func)0;
+               session->c_stream.zfree = (free_func)0;
+               session->c_stream.opaque = (voidpf)0;
+
+               session->d_stream.zalloc = (alloc_func)0;
+               session->d_stream.zfree = (free_func)0;
+               session->d_stream.opaque = (voidpf)0;
+
+               /* If we cant call this, well, we're boned. */
+               if (inflateInit(&session->d_stream) != Z_OK)
+               {
+                       session->status = IZIP_CLOSED;
+                       return;
+               }
+
+               /* Same here */
+               if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
+               {
+                       inflateEnd(&session->d_stream);
+                       session->status = IZIP_CLOSED;
+                       return;
+               }
+
+               /* Just in case, do this last */
+               session->status = IZIP_OPEN;
+       }
+
+       void OnStreamSocketClose(StreamSocket* user)
+       {
+               int fd = user->GetFd();
+               CloseSession(&sessions[fd]);
+       }
+
+       int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
+       {
+               int fd = user->GetFd();
+               /* Find the sockets session */
+               izip_session* session = &sessions[fd];
+
+               if (session->status == IZIP_CLOSED)
+                       return -1;
+
+               if (session->inbuf.empty())
+               {
+                       /* Read read_buffer_size bytes at a time to the buffer (usually 2.5k) */
+                       int readresult = read(fd, net_buffer, net_buffer_size);
+
+                       if (readresult < 0)
+                       {
+                               if (errno == EINTR || errno == EAGAIN)
+                                       return 0;
+                       }
+                       if (readresult <= 0)
+                               return -1;
+
+                       total_in_compressed += readresult;
+
+                       /* Copy the compressed data into our input buffer */
+                       session->inbuf.append(net_buffer, readresult);
+               }
+
+               size_t in_len = session->inbuf.length();
+               char* buffer = ServerInstance->GetReadBuffer();
+               int count = ServerInstance->Config->NetBufferSize;
+
+               /* Prepare decompression */
+               session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
+               session->d_stream.avail_in = in_len;
+
+               session->d_stream.next_out = (Bytef*)buffer;
+               /* Last byte is reserved for NULL terminating that beast */
+               session->d_stream.avail_out = count - 1;
+
+               /* Z_SYNC_FLUSH: Do as much as possible */
+               int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
+               /* TODO CloseStream() in here at random places */
+               switch (ret)
+               {
+                       case Z_NEED_DICT:
+                       case Z_STREAM_ERROR:
+                               /* This is one of the 'not supposed to happen' things.
+                                * Memory corruption, anyone?
+                                */
+                               Error(session, "General Error. This is not supposed to happen :/");
+                               break;
+                       case Z_DATA_ERROR:
+                               Error(session, "Decompression failed, malformed data");
+                               break;
+                       case Z_MEM_ERROR:
+                               Error(session, "Out of memory");
+                               break;
+                       case Z_BUF_ERROR:
+                               /* This one is non-fatal, buffer is just full
+                                * (can't happen here).
+                                */
+                               Error(session, "Internal error. This is not supposed to happen.");
+                               break;
+                       case Z_STREAM_END:
+                               /* This module *never* generates these :/ */
+                               Error(session, "End-of-stream marker received");
+                               break;
+                       case Z_OK:
+                               break;
+                       default:
+                               /* NO WAI! This can't happen. All errors are handled above. */
+                               Error(session, "Unknown error");
+                               break;
+               }
+               if (ret != Z_OK)
+               {
+                       return -1;
+               }
+
+               /* Update the inbut buffer */
+               unsigned int input_compressed = in_len - session->d_stream.avail_in;
+               session->inbuf = session->inbuf.substr(input_compressed);
+
+               /* Update counters (Old size - new size) */
+               unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
+               total_in_uncompressed += uncompressed_length;
+
+               /* Null-terminate the buffer -- this doesnt harm binary data */
+               recvq.append(buffer, uncompressed_length);
+               return 1;
+       }
+
+       int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
+       {
+               int fd = user->GetFd();
+               izip_session* session = &sessions[fd];
+
+               if(session->status != IZIP_OPEN)
+                       /* Seriously, wtf? */
+                       return -1;
+
+               int ret;
+
+               /* This loop is really only supposed to run once, but in case 'compr'
+                * is filled up somehow we are prepared to handle this situation.
+                */
+               unsigned int offset = 0;
+               do
+               {
+                       /* Prepare compression */
+                       session->c_stream.next_in = (Bytef*)sendq.data() + offset;
+                       session->c_stream.avail_in = sendq.length() - offset;
+
+                       session->c_stream.next_out = (Bytef*)net_buffer;
+                       session->c_stream.avail_out = net_buffer_size;
+
+                       /* Compress the text */
+                       ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
+                       /* TODO CloseStream() in here at random places */
+                       switch (ret)
+                       {
+                               case Z_OK:
+                                       break;
+                               case Z_BUF_ERROR:
+                                       /* This one is non-fatal, buffer is just full
+                                        * (can't happen here).
+                                        */
+                                       Error(session, "Internal error. This is not supposed to happen.");
+                                       break;
+                               case Z_STREAM_ERROR:
+                                       /* This is one of the 'not supposed to happen' things.
+                                        * Memory corruption, anyone?
+                                        */
+                                       Error(session, "General Error. This is also not supposed to happen.");
+                                       break;
+                               default:
+                                       Error(session, "Unknown error");
+                                       break;
+                       }
+
+                       if (ret != Z_OK)
+                               return 0;
+
+                       /* Space before - space after stuff was added to this */
+                       unsigned int compressed = net_buffer_size - session->c_stream.avail_out;
+                       unsigned int uncompressed = sendq.length() - session->c_stream.avail_in;
+
+                       /* Make it skip the data which was compressed already */
+                       offset += uncompressed;
+
+                       /* Update stats */
+                       total_out_uncompressed += uncompressed;
+                       total_out_compressed += compressed;
+
+                       /* Add compressed to the output buffer */
+                       session->outbuf.append((const char*)net_buffer, compressed);
+               } while (session->c_stream.avail_in != 0);
+
+               /* Lets see how much we can send out */
+               ret = write(fd, session->outbuf.data(), session->outbuf.length());
+
+               /* Check for errors, and advance the buffer if any was sent */
+               if (ret > 0)
+                       session->outbuf = session->outbuf.substr(ret);
+               else if (ret < 1)
+               {
+                       if (errno == EAGAIN)
+                               return 0;
+                       else
+                       {
+                               session->outbuf.clear();
+                               return -1;
+                       }
+               }
+
+               return 1;
+       }
+
+       void Error(izip_session* session, const std::string &text)
+       {
+               ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
+       }
+
+       void CloseSession(izip_session* session)
+       {
+               if (session->status == IZIP_OPEN)
+               {
+                       session->status = IZIP_CLOSED;
+                       session->outbuf.clear();
+                       inflateEnd(&session->d_stream);
+                       deflateEnd(&session->c_stream);
+               }
+       }
+
+};
+
+MODULE_INIT(ModuleZLib)
+