]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ziplink.cpp
2aeb4b9e6d37c23c397c5a777d08d076bfea5adb
[user/henk/code/inspircd.git] / src / modules / extra / m_ziplink.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <zlib.h>
16 #include <iostream>
17
18 /* $ModDesc: Provides zlib link support for servers */
19 /* $LinkerFlags: -lz */
20
21 /*
22  * ZLIB_BEST_COMPRESSION (9) is used for all sending of data with
23  * a flush after each chunk. A frame may contain multiple lines
24  * and should be treated as raw binary data.
25  */
26
27 /* Status of a connection */
28 enum izip_status { IZIP_CLOSED = 0, IZIP_OPEN };
29
30 /** Represents an zipped connections extra data
31  */
32 class izip_session
33 {
34  public:
35         z_stream c_stream;      /* compression stream */
36         z_stream d_stream;      /* uncompress stream */
37         izip_status status;     /* Connection status */
38         std::string outbuf;     /* Holds output buffer (compressed) */
39         std::string inbuf;      /* Holds input buffer (compressed) */
40 };
41
42 class ModuleZLib : public Module
43 {
44         izip_session* sessions;
45
46         /* Used for stats z extensions */
47         float total_out_compressed;
48         float total_in_compressed;
49         float total_out_uncompressed;
50         float total_in_uncompressed;
51
52         /* Used for reading data from the wire and compressing data to. */
53         char *net_buffer;
54         unsigned int net_buffer_size;
55  public:
56
57         ModuleZLib()
58         {
59                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
60
61                 sessions = new izip_session[ServerInstance->SE->GetMaxFds()];
62                 for (int i = 0; i < ServerInstance->SE->GetMaxFds(); i++)
63                         sessions[i].status = IZIP_CLOSED;
64
65                 total_out_compressed = total_in_compressed = 0;
66                 total_out_uncompressed = total_in_uncompressed = 0;
67                 Implementation eventlist[] = { I_OnStats };
68                 ServerInstance->Modules->Attach(eventlist, this, 1);
69
70                 // Allocate a buffer which is used for reading and writing data
71                 net_buffer_size = ServerInstance->Config->NetBufferSize;
72                 net_buffer = new char[net_buffer_size];
73         }
74
75         ~ModuleZLib()
76         {
77                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
78                 delete[] sessions;
79                 delete[] net_buffer;
80         }
81
82         Version GetVersion()
83         {
84                 return Version("Provides zlib link support for servers", VF_VENDOR);
85         }
86
87         /* Handle stats z (misc stats) */
88         ModResult OnStats(char symbol, User* user, string_list &results)
89         {
90                 if (symbol == 'z')
91                 {
92                         std::string sn = ServerInstance->Config->ServerName;
93
94                         /* Yeah yeah, i know, floats are ew.
95                          * We used them here because we'd be casting to float anyway to do this maths,
96                          * and also only floating point numbers can deal with the pretty large numbers
97                          * involved in the total throughput of a server over a large period of time.
98                          * (we dont count 64 bit ints because not all systems have 64 bit ints, and floats
99                          * can still hold more.
100                          */
101                         float outbound_r = (total_out_compressed / (total_out_uncompressed + 0.001)) * 100;
102                         float inbound_r = (total_in_compressed / (total_in_uncompressed + 0.001)) * 100;
103
104                         float total_compressed = total_in_compressed + total_out_compressed;
105                         float total_uncompressed = total_in_uncompressed + total_out_uncompressed;
106
107                         float total_r = (total_compressed / (total_uncompressed + 0.001)) * 100;
108
109                         char outbound_ratio[MAXBUF], inbound_ratio[MAXBUF], combined_ratio[MAXBUF];
110
111                         sprintf(outbound_ratio, "%3.2f%%", outbound_r);
112                         sprintf(inbound_ratio, "%3.2f%%", inbound_r);
113                         sprintf(combined_ratio, "%3.2f%%", total_r);
114
115                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_compressed   = "+ConvToStr(total_out_compressed));
116                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_compressed    = "+ConvToStr(total_in_compressed));
117                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS outbound_uncompressed = "+ConvToStr(total_out_uncompressed));
118                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS inbound_uncompressed  = "+ConvToStr(total_in_uncompressed));
119                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_original_outbound_traffic        = "+outbound_ratio);
120                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS percentage_of_orignal_inbound_traffic         = "+inbound_ratio);
121                         results.push_back(sn+" 304 "+user->nick+" :ZIPSTATS total_size_of_original_traffic        = "+combined_ratio);
122                         return MOD_RES_PASSTHRU;
123                 }
124
125                 return MOD_RES_PASSTHRU;
126         }
127
128         void OnStreamSocketConnect(StreamSocket* user)
129         {
130                 OnStreamSocketAccept(user, 0, 0);
131         }
132
133         void OnRawSocketAccept(StreamSocket* user, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*)
134         {
135                 int fd = user->GetFd();
136
137                 izip_session* session = &sessions[fd];
138
139                 /* Just in case... */
140                 session->outbuf.clear();
141
142                 session->c_stream.zalloc = (alloc_func)0;
143                 session->c_stream.zfree = (free_func)0;
144                 session->c_stream.opaque = (voidpf)0;
145
146                 session->d_stream.zalloc = (alloc_func)0;
147                 session->d_stream.zfree = (free_func)0;
148                 session->d_stream.opaque = (voidpf)0;
149
150                 /* If we cant call this, well, we're boned. */
151                 if (inflateInit(&session->d_stream) != Z_OK)
152                 {
153                         session->status = IZIP_CLOSED;
154                         return;
155                 }
156
157                 /* Same here */
158                 if (deflateInit(&session->c_stream, Z_BEST_COMPRESSION) != Z_OK)
159                 {
160                         inflateEnd(&session->d_stream);
161                         session->status = IZIP_CLOSED;
162                         return;
163                 }
164
165                 /* Just in case, do this last */
166                 session->status = IZIP_OPEN;
167         }
168
169         void OnStreamSocketClose(StreamSocket* user)
170         {
171                 int fd = user->GetFd();
172                 CloseSession(&sessions[fd]);
173         }
174
175         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
176         {
177                 int fd = user->GetFd();
178                 /* Find the sockets session */
179                 izip_session* session = &sessions[fd];
180
181                 if (session->status == IZIP_CLOSED)
182                         return -1;
183
184                 if (session->inbuf.empty())
185                 {
186                         /* Read read_buffer_size bytes at a time to the buffer (usually 2.5k) */
187                         int readresult = read(fd, net_buffer, net_buffer_size);
188
189                         if (readresult < 0)
190                         {
191                                 if (errno == EINTR || errno == EAGAIN)
192                                         return 0;
193                         }
194                         if (readresult <= 0)
195                                 return -1;
196
197                         total_in_compressed += readresult;
198
199                         /* Copy the compressed data into our input buffer */
200                         session->inbuf.append(net_buffer, readresult);
201                 }
202
203                 size_t in_len = session->inbuf.length();
204                 char* buffer = ServerInstance->GetReadBuffer();
205                 int count = ServerInstance->Config->NetBufferSize;
206
207                 /* Prepare decompression */
208                 session->d_stream.next_in = (Bytef *)session->inbuf.c_str();
209                 session->d_stream.avail_in = in_len;
210
211                 session->d_stream.next_out = (Bytef*)buffer;
212                 /* Last byte is reserved for NULL terminating that beast */
213                 session->d_stream.avail_out = count - 1;
214
215                 /* Z_SYNC_FLUSH: Do as much as possible */
216                 int ret = inflate(&session->d_stream, Z_SYNC_FLUSH);
217                 /* TODO CloseStream() in here at random places */
218                 switch (ret)
219                 {
220                         case Z_NEED_DICT:
221                         case Z_STREAM_ERROR:
222                                 /* This is one of the 'not supposed to happen' things.
223                                  * Memory corruption, anyone?
224                                  */
225                                 Error(session, "General Error. This is not supposed to happen :/");
226                                 break;
227                         case Z_DATA_ERROR:
228                                 Error(session, "Decompression failed, malformed data");
229                                 break;
230                         case Z_MEM_ERROR:
231                                 Error(session, "Out of memory");
232                                 break;
233                         case Z_BUF_ERROR:
234                                 /* This one is non-fatal, buffer is just full
235                                  * (can't happen here).
236                                  */
237                                 Error(session, "Internal error. This is not supposed to happen.");
238                                 break;
239                         case Z_STREAM_END:
240                                 /* This module *never* generates these :/ */
241                                 Error(session, "End-of-stream marker received");
242                                 break;
243                         case Z_OK:
244                                 break;
245                         default:
246                                 /* NO WAI! This can't happen. All errors are handled above. */
247                                 Error(session, "Unknown error");
248                                 break;
249                 }
250                 if (ret != Z_OK)
251                 {
252                         return -1;
253                 }
254
255                 /* Update the inbut buffer */
256                 unsigned int input_compressed = in_len - session->d_stream.avail_in;
257                 session->inbuf = session->inbuf.substr(input_compressed);
258
259                 /* Update counters (Old size - new size) */
260                 unsigned int uncompressed_length = (count - 1) - session->d_stream.avail_out;
261                 total_in_uncompressed += uncompressed_length;
262
263                 /* Null-terminate the buffer -- this doesnt harm binary data */
264                 recvq.append(buffer, uncompressed_length);
265                 return 1;
266         }
267
268         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
269         {
270                 int fd = user->GetFd();
271                 izip_session* session = &sessions[fd];
272
273                 if(session->status != IZIP_OPEN)
274                         /* Seriously, wtf? */
275                         return -1;
276
277                 int ret;
278
279                 /* This loop is really only supposed to run once, but in case 'compr'
280                  * is filled up somehow we are prepared to handle this situation.
281                  */
282                 unsigned int offset = 0;
283                 do
284                 {
285                         /* Prepare compression */
286                         session->c_stream.next_in = (Bytef*)sendq.data() + offset;
287                         session->c_stream.avail_in = sendq.length() - offset;
288
289                         session->c_stream.next_out = (Bytef*)net_buffer;
290                         session->c_stream.avail_out = net_buffer_size;
291
292                         /* Compress the text */
293                         ret = deflate(&session->c_stream, Z_SYNC_FLUSH);
294                         /* TODO CloseStream() in here at random places */
295                         switch (ret)
296                         {
297                                 case Z_OK:
298                                         break;
299                                 case Z_BUF_ERROR:
300                                         /* This one is non-fatal, buffer is just full
301                                          * (can't happen here).
302                                          */
303                                         Error(session, "Internal error. This is not supposed to happen.");
304                                         break;
305                                 case Z_STREAM_ERROR:
306                                         /* This is one of the 'not supposed to happen' things.
307                                          * Memory corruption, anyone?
308                                          */
309                                         Error(session, "General Error. This is also not supposed to happen.");
310                                         break;
311                                 default:
312                                         Error(session, "Unknown error");
313                                         break;
314                         }
315
316                         if (ret != Z_OK)
317                                 return 0;
318
319                         /* Space before - space after stuff was added to this */
320                         unsigned int compressed = net_buffer_size - session->c_stream.avail_out;
321                         unsigned int uncompressed = sendq.length() - session->c_stream.avail_in;
322
323                         /* Make it skip the data which was compressed already */
324                         offset += uncompressed;
325
326                         /* Update stats */
327                         total_out_uncompressed += uncompressed;
328                         total_out_compressed += compressed;
329
330                         /* Add compressed to the output buffer */
331                         session->outbuf.append((const char*)net_buffer, compressed);
332                 } while (session->c_stream.avail_in != 0);
333
334                 /* Lets see how much we can send out */
335                 ret = write(fd, session->outbuf.data(), session->outbuf.length());
336
337                 /* Check for errors, and advance the buffer if any was sent */
338                 if (ret > 0)
339                         session->outbuf = session->outbuf.substr(ret);
340                 else if (ret < 1)
341                 {
342                         if (errno == EAGAIN)
343                                 return 0;
344                         else
345                         {
346                                 session->outbuf.clear();
347                                 return -1;
348                         }
349                 }
350
351                 return 1;
352         }
353
354         void Error(izip_session* session, const std::string &text)
355         {
356                 ServerInstance->SNO->WriteToSnoMask('l', "ziplink error: " + text);
357         }
358
359         void CloseSession(izip_session* session)
360         {
361                 if (session->status == IZIP_OPEN)
362                 {
363                         session->status = IZIP_CLOSED;
364                         session->outbuf.clear();
365                         inflateEnd(&session->d_stream);
366                         deflateEnd(&session->c_stream);
367                 }
368         }
369
370 };
371
372 MODULE_INIT(ModuleZLib)
373