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