]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/userprocess.cpp
f8d7218cf43051f38835008577a1a11cc3585a4f
[user/henk/code/inspircd.git] / src / userprocess.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* Now with added unF! ;) */
18
19 using namespace std;
20
21 #include "inspircd_config.h"
22 #include "inspircd.h"
23 #include "inspircd_io.h"
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/errno.h>
27 #include <sys/ioctl.h>
28 #include <sys/utsname.h>
29 #include <time.h>
30 #include <string>
31 #ifdef GCC3
32 #include <ext/hash_map>
33 #else
34 #include <hash_map>
35 #endif
36 #include <map>
37 #include <sstream>
38 #include <vector>
39 #include <deque>
40 #include <sched.h>
41 #ifdef THREADED_DNS
42 #include <pthread.h>
43 #endif
44 #include "users.h"
45 #include "ctables.h"
46 #include "globals.h"
47 #include "modules.h"
48 #include "dynamic.h"
49 #include "wildcard.h"
50 #include "message.h"
51 #include "mode.h"
52 #include "commands.h"
53 #include "xline.h"
54 #include "inspstring.h"
55 #include "dnsqueue.h"
56 #include "helperfuncs.h"
57 #include "hashcomp.h"
58 #include "socketengine.h"
59 #include "typedefs.h"
60
61 extern int MODCOUNT;
62 extern struct sockaddr_in client,server;
63 extern socklen_t length;
64 extern std::vector<Module*> modules;
65 extern std::vector<ircd_module*> factory;
66 extern std::vector<InspSocket*> module_sockets;
67 extern time_t TIME;
68 extern time_t OLDTIME;
69 extern std::vector<userrec*> local_users;
70
71 extern InspIRCd* ServerInstance;
72 extern SocketEngine* SE;
73 extern serverstats* stats;
74 extern ServerConfig *Config;
75
76 extern userrec* fd_ref_table[65536];
77 char data[65536];
78
79 extern user_hash clientlist;
80 extern chan_hash chanlist;
81
82 extern Module* IOHookModule;
83
84 void ProcessUser(userrec* cu)
85 {
86         int result = EAGAIN;
87         log(DEBUG,"Processing user with fd %d",cu->fd);
88         if (IOHookModule)
89         {
90                 int MOD_RESULT = 0;
91                 int result2 = 0;
92                 IOHookModule->OnRawSocketRead(cu->fd,data,65535,result2);
93                 if (!MOD_RESULT)
94                 {
95                         result = cu->ReadData(data, 65535);
96                 }
97                 else
98                 {
99                         log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
100                         result = result2;
101                 }
102         }
103         else
104         {
105                 result = cu->ReadData(data, 65535);
106         }
107         log(DEBUG,"Read result: %d",result);
108         if (result)
109         {
110                 stats->statsRecv += result;
111                 // perform a check on the raw buffer as an array (not a string!) to remove
112                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
113                 // hopefully this should stop even more people whining about "Unknown command: *"
114                 for (int checker = 0; checker < result; checker++)
115                 {
116                         if ((data[checker] == 0) || (data[checker] == 7))
117                                 data[checker] = ' ';
118                 }
119                 if (result > 0)
120                         data[result] = '\0';
121                 userrec* current = cu;
122                 int currfd = current->fd;
123                 int floodlines = 0;
124                 // add the data to the users buffer
125                 if (result > 0)
126                 {
127                         if (!current->AddBuffer(data))
128                         {
129                                 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
130                                 if (current->registered == 7)
131                                 {
132                                         kill_link(current,"RecvQ exceeded");
133                                 }
134                                 else
135                                 {
136                                         WriteOpers("*** Excess flood from %s",current->ip);
137                                         log(DEFAULT,"Excess flood from: %s",current->ip);
138                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
139                                         apply_lines(APPLY_ZLINES);
140                                 }
141                                 return;
142                         }
143                         if (current->recvq.length() > (unsigned)Config->NetBufferSize)
144                         {
145                                 if (current->registered == 7)
146                                 {
147                                         kill_link(current,"RecvQ exceeded");
148                                 }
149                                 else
150                                 {
151                                         WriteOpers("*** Excess flood from %s",current->ip);
152                                         log(DEFAULT,"Excess flood from: %s",current->ip);
153                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
154                                         apply_lines(APPLY_ZLINES);
155                                 }
156                                 return;
157                         }
158                         // while there are complete lines to process...
159                         while (current->BufferIsReady())
160                         {
161                                 floodlines++;
162                                 if (TIME > current->reset_due)
163                                 {
164                                         current->reset_due = TIME + current->threshold;
165                                         current->lines_in = 0;
166                                 }
167                                 current->lines_in++;
168                                 if (current->lines_in > current->flood)
169                                 {
170                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
171                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
172                                         kill_link(current,"Excess flood");
173                                         return;
174                                 }
175                                 if ((floodlines > current->flood) && (current->flood != 0))
176                                 {
177                                         if (current->registered == 7)
178                                         {
179                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
180                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
181                                                 kill_link(current,"Excess flood");
182                                         }
183                                         else
184                                         {
185                                                 add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
186                                                 apply_lines(APPLY_ZLINES);
187                                         }
188                                         return;
189                                 }
190                                 char sanitized[MAXBUF];
191                                 // use GetBuffer to copy single lines into the sanitized string
192                                 std::string single_line = current->GetBuffer();
193                                 current->bytes_in += single_line.length();
194                                 current->cmds_in++;
195                                 if (single_line.length()>512)
196                                 {
197                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
198                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
199                                         kill_link(current,"Excess flood");
200                                         return;
201                                 }
202                                 strlcpy(sanitized,single_line.c_str(),MAXBUF);
203                                 if (*sanitized)
204                                 {
205                                         userrec* old_comp = fd_ref_table[currfd];
206                                         // we're gonna re-scan to check if the nick is gone, after every
207                                         // command - if it has, we're gonna bail
208                                         process_buffer(sanitized,current);
209                                         // look for the user's record in case it's changed... if theyve quit,
210                                         // we cant do anything more with their buffer, so bail.
211                                         // there used to be an ugly, slow loop here. Now we have a reference
212                                         // table, life is much easier (and FASTER)
213                                         userrec* new_comp = fd_ref_table[currfd];
214                                         if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
215                                         {
216                                                 return;
217                                         }
218                                         else
219                                         {
220                                                 /* The user is still here, flush their buffer */
221                                                 current->FlushWriteBuf();
222                                         }
223                                 }
224                         }
225                         return;
226                 }
227                 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
228                 {
229                         log(DEBUG,"killing: %s",cu->nick);
230                         kill_link(cu,strerror(errno));
231                         return;
232                 }
233         }
234         // result EAGAIN means nothing read
235         else if (result == EAGAIN)
236         {
237         }
238         else if (result == 0)
239         {
240                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
241                 kill_link(cu,"Client exited");
242                 log(DEBUG,"Bailing from client exit");
243                 return;
244         }
245 }
246
247
248 /**
249  * This function is called once a second from the mainloop.
250  * It is intended to do background checking on all the user structs, e.g.
251  * stuff like ping checks, registration timeouts, etc.
252  * The function returns false when it is finished, and true if
253  * it needs to be run again (e.g. it has processed one of a batch of
254  * QUIT messages, but couldnt continue iterating because the iterator
255  * became invalid). This function is also responsible for checking
256  * if InspSocket derived classes are timed out.
257  */
258 bool DoBackgroundUserStuff(time_t TIME)
259 {
260         unsigned int numsockets = module_sockets.size();
261         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
262         {
263                 InspSocket* s = (InspSocket*)*a;
264                 if (s->Timeout(TIME))
265                 {
266                         log(DEBUG,"Socket poll returned false, close and bail");
267                         SE->DelFd(s->GetFd());
268                         s->Close();
269                         module_sockets.erase(a);
270                         delete s;
271                         break;
272                 }
273                 if (module_sockets.size() != numsockets) break;
274         }
275         /* TODO: We need a seperate hash containing only local users for this
276          */
277         for (std::vector<userrec*>::iterator count2 = local_users.begin(); count2 != local_users.end(); count2++)
278         {
279                 /* Sanity checks for corrupted iterators (yes, really) */
280                 userrec* curr = NULL;
281                 if (*count2)
282                         curr = (userrec*)(*count2);
283                 if ((long)curr == -1)
284                         return false;
285
286                 if ((curr) && (curr->fd != 0)) /* XXX - why are we checking fd != 0? --w00t */
287                 {
288                         int currfd = curr->fd;
289                         // we don't check the state of remote users.
290                         if (IS_LOCAL(curr))
291                         {
292                                 curr->FlushWriteBuf();
293                                 if (curr->GetWriteError() != "")
294                                 {
295                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
296                                         kill_link(curr,curr->GetWriteError().c_str());
297                                         return true;
298                                 }
299                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
300                                 // their connection class.
301                                 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
302                                 {
303                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
304                                         kill_link(curr,"Registration timeout");
305                                         return true;
306                                 }
307                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
308                                 {
309                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
310                                         curr->dns_done = true;
311                                         stats->statsDnsBad++;
312                                         FullConnectUser(curr);
313                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
314                                                 return true;
315                                  }
316                                  if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
317                                  {
318                                        log(DEBUG,"dns done, registered=3, and modules ready, OK");
319                                        FullConnectUser(curr);
320                                        if (fd_ref_table[currfd] != curr) // something changed, bail pronto
321                                                 return true;
322                                  }
323                                  if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
324                                  {
325                                        if ((!curr->lastping) && (curr->registered == 7))
326                                        {
327                                                log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
328                                                kill_link(curr,"Ping timeout");
329                                                return true;
330                                        }
331                                        Write(curr->fd,"PING :%s",Config->ServerName);
332                                        log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
333                                        curr->lastping = 0;
334                                        curr->nping = TIME+curr->pingmax;       // was hard coded to 120
335                                 }
336                         }
337                 }
338         }
339         return false;
340 }
341
342 void OpenLog(char** argv, int argc)
343 {
344         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
345         Config->log_file = fopen(logpath.c_str(),"a+");
346         if (!Config->log_file)
347         {
348                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
349                 Exit(ERROR);
350         }
351 #ifdef IS_CYGWIN
352         printf("Logging to ircd.log...\n");
353 #else
354         printf("Logging to %s...\n",logpath.c_str());
355 #endif
356 }
357
358
359 void CheckRoot()
360 {
361         if (geteuid() == 0)
362         {
363                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
364                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
365                 Exit(ERROR);
366         }
367 }
368
369
370 void CheckDie()
371 {
372         if (*Config->DieValue)
373         {
374                 printf("WARNING: %s\n\n",Config->DieValue);
375                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",Config->DieValue);
376                 exit(0);
377         }
378 }
379
380 void LoadAllModules()
381 {
382         /* We must load the modules AFTER initializing the socket engine, now */
383         MODCOUNT = -1;
384         char configToken[MAXBUF];
385         for (int count = 0; count < Config->ConfValueEnum("module",&Config->config_f); count++)
386         {
387                 Config->ConfValue("module","name",count,configToken,&Config->config_f);
388                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
389                 if (!ServerInstance->LoadModule(configToken))
390                 {
391                         log(DEFAULT,"Exiting due to a module loader error.");
392                         printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ServerInstance->ModuleError());
393                         Exit(0);
394                 }
395         }
396         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
397 }
398
399