]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/userprocess.cpp
More cleanup
[user/henk/code/inspircd.git] / src / userprocess.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 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 "userprocess.h"
60 #include "typedefs.h"
61 #include "command_parse.h"
62 #include "cull_list.h"
63
64 extern int MODCOUNT;
65 extern struct sockaddr_in client,server;
66 extern socklen_t length;
67 extern std::vector<Module*> modules;
68 extern std::vector<ircd_module*> factory;
69 extern std::vector<InspSocket*> module_sockets;
70 extern time_t TIME;
71 extern time_t OLDTIME;
72 extern std::vector<userrec*> local_users;
73 char LOG_FILE[MAXBUF];
74
75 extern InspIRCd* ServerInstance;
76 extern ServerConfig *Config;
77 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
78 char data[65536];
79
80 extern user_hash clientlist;
81 extern chan_hash chanlist;
82
83 void ProcessUser(userrec* cu)
84 {
85         int result = EAGAIN;
86
87         if (cu->fd == FD_MAGIC_NUMBER)
88                 return;
89
90         log(DEBUG,"Processing user with fd %d",cu->fd);
91
92         if (Config->GetIOHook(cu->port))
93         {
94                 int result2 = 0;
95                 int MOD_RESULT = 0;
96
97                 try
98                 {
99                         MOD_RESULT = Config->GetIOHook(cu->port)->OnRawSocketRead(cu->fd,data,65535,result2);
100                         log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
101                 }
102                 catch (ModuleException& modexcept)
103                 {
104                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \
105                 }
106
107                 if (MOD_RESULT < 0)
108                 {
109                         result = -EAGAIN;
110                 }
111                 else
112                 {
113                         result = result2;
114                 }
115         }
116         else
117         {
118                 result = cu->ReadData(data, 65535);
119         }
120
121         log(DEBUG,"Read result: %d",result);
122
123         if ((result) && (result != -EAGAIN))
124         {
125                 userrec *current;
126                 int currfd;
127                 int floodlines;
128
129                 ServerInstance->stats->statsRecv += result;
130                 /*
131                  * perform a check on the raw buffer as an array (not a string!) to remove
132                  * characters 0 and 7 which are illegal in the RFC - replace them with spaces.
133                  * hopefully this should stop even more people whining about "Unknown command: *"
134                  */
135
136                 /*
137                  * XXX - potential replacement for the below using my beloved pointers. --w00t
138                  *
139                  * for (char *c = data; data && *data; data++)
140                  * {
141                  *      if (*data == 0 || *data == 7)
142                  *              data = ' ';
143                  * }
144                  */
145
146                 for (int checker = 0; checker < result; checker++)
147                 {
148                         if ((data[checker] == 0) || (data[checker] == 7))
149                                 data[checker] = ' ';
150                 }
151
152                 if (result > 0)
153                         data[result] = '\0';
154
155                 current = cu;
156                 currfd = current->fd;
157                 floodlines = 0;
158
159                 // add the data to the users buffer
160                 if (result > 0)
161                 {
162                         if (!current->AddBuffer(data))
163                         {
164                                 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
165                                 if (current->registered == 7)
166                                 {
167                                         // Make sure they arn't flooding long lines.
168                                         if (TIME > current->reset_due)
169                                         {
170                                                 current->reset_due = TIME + current->threshold;
171                                                 current->lines_in = 0;
172                                         }
173
174                                         current->lines_in++;
175
176                                         if (current->lines_in > current->flood)
177                                         {
178                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
179                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
180                                                 kill_link(current,"Excess flood");
181                                                 return;
182                                         }
183                                         else
184                                         {
185                                                 WriteServ(currfd, "NOTICE %s :Your previous line was too long and was not delivered (Over 512chars) Please shorten it.", current->nick);
186                                                 current->recvq = "";
187                                         }
188                                 }
189                                 else
190                                 {
191                                         WriteOpers("*** Excess flood from %s",(char*)inet_ntoa(current->ip4));
192                                         log(DEFAULT,"Excess flood from: %s",(char*)inet_ntoa(current->ip4));
193                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",(char*)inet_ntoa(current->ip4));
194                                         apply_lines(APPLY_ZLINES);
195                                 }
196
197                                 return;
198                         }
199
200                         if (current->recvq.length() > (unsigned)Config->NetBufferSize)
201                         {
202                                 if (current->registered == 7)
203                                 {
204                                         kill_link(current,"RecvQ exceeded");
205                                 }
206                                 else
207                                 {
208                                         WriteOpers("*** Excess flood from %s",(char*)inet_ntoa(current->ip4));
209                                         log(DEFAULT,"Excess flood from: %s",(char*)inet_ntoa(current->ip4));
210                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",(char*)inet_ntoa(current->ip4));
211                                         apply_lines(APPLY_ZLINES);
212                                 }
213
214                                 return;
215                         }
216
217                         // while there are complete lines to process...
218                         while (current->BufferIsReady())
219                         {
220                                 char sanitized[MAXBUF];
221
222                                 floodlines++;
223                                 if (TIME > current->reset_due)
224                                 {
225                                         current->reset_due = TIME + current->threshold;
226                                         current->lines_in = 0;
227                                 }
228
229                                 current->lines_in++;
230
231                                 if (current->lines_in > current->flood)
232                                 {
233                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
234                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
235                                         kill_link(current,"Excess flood");
236                                         return;
237                                 }
238
239                                 if ((floodlines > current->flood) && (current->flood != 0))
240                                 {
241                                         if (current->registered == 7)
242                                         {
243                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
244                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
245                                                 kill_link(current,"Excess flood");
246                                         }
247                                         else
248                                         {
249                                                 add_zline(120,Config->ServerName,"Flood from unregistered connection",(char*)inet_ntoa(current->ip4));
250                                                 apply_lines(APPLY_ZLINES);
251                                         }
252
253                                         return;
254                                 }
255
256                                 // use GetBuffer to copy single lines into the sanitized string
257                                 std::string single_line = current->GetBuffer();
258                                 current->bytes_in += single_line.length();
259                                 current->cmds_in++;
260                                 strlcpy(sanitized,single_line.c_str(),511);
261
262                                 if (*sanitized)
263                                 {
264                                         userrec* old_comp = fd_ref_table[currfd];
265
266                                         ServerInstance->Parser->ProcessBuffer(sanitized,current);
267                                         /*
268                                          * look for the user's record in case it's changed... if theyve quit,
269                                          * we cant do anything more with their buffer, so bail.
270                                          * there used to be an ugly, slow loop here. Now we have a reference
271                                          * table, life is much easier (and FASTER)
272                                          */
273                                         userrec* new_comp = fd_ref_table[currfd];
274                                         if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
275                                         {
276                                                 return;
277                                         }
278                                         else
279                                         {
280                                                 /* The user is still here, flush their buffer */
281                                                 current->FlushWriteBuf();
282                                         }
283                                 }
284                         }
285
286                         return;
287                 }
288
289                 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
290                 {
291                         log(DEBUG,"killing: %s",cu->nick);
292                         kill_link(cu,strerror(errno));
293                         return;
294                 }
295         }
296
297         // result EAGAIN means nothing read
298         else if ((result == EAGAIN) || (result == -EAGAIN))
299         {
300                 /* do nothing */
301         }
302         else if (result == 0)
303         {
304                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
305                 kill_link(cu,"Client exited");
306                 log(DEBUG,"Bailing from client exit");
307                 return;
308         }
309 }
310
311 void DoSocketTimeouts(time_t TIME)
312 {
313         unsigned int numsockets = module_sockets.size();
314         SocketEngine* SE = ServerInstance->SE;
315
316         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
317         {
318                 InspSocket* s = (InspSocket*)*a;
319                 if (s->Timeout(TIME))
320                 {
321                         log(DEBUG,"Socket poll returned false, close and bail");
322                         SE->DelFd(s->GetFd());
323                         s->Close();
324                         module_sockets.erase(a);
325                         delete s;
326                         break;
327                 }
328
329                 if (module_sockets.size() != numsockets)
330                         break;
331         }
332 }
333
334 /**
335  * This function is called once a second from the mainloop.
336  * It is intended to do background checking on all the user structs, e.g.
337  * stuff like ping checks, registration timeouts, etc. This function is
338  * also responsible for checking if InspSocket derived classes are timed out.
339  */
340 void DoBackgroundUserStuff(time_t TIME)
341 {
342         CullList* GlobalGoners = new CullList();
343
344         for (std::vector<userrec*>::iterator count2 = local_users.begin(); count2 != local_users.end(); count2++)
345         {
346                 /* Sanity checks for corrupted iterators (yes, really) */
347                 userrec* curr = NULL;
348
349                 if (*count2)
350                         curr = (userrec*)(*count2);
351                 if ((long)curr == -1)
352                         return;
353
354                 if (curr)
355                 {
356                         /*
357                          * registration timeout -- didnt send USER/NICK/HOST
358                          * in the time specified in their connection class.
359                          */
360                         if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
361                         {
362                                 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
363                                 GlobalGoners->AddItem(curr,"Registration timeout");
364                                 continue;
365                         }
366
367                         /*
368                          * user has signed on with USER/NICK/PASS, and dns has completed, all the modules
369                          * say this user is ok to proceed, fully connect them.
370                          */
371                         if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
372                         {
373                                 curr->dns_done = true;
374                                 ServerInstance->stats->statsDnsBad++;
375                                 FullConnectUser(curr,GlobalGoners);
376                                 continue;
377                         }
378
379                         if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
380                         {
381                                 log(DEBUG,"dns done, registered=3, and modules ready, OK");
382                                 FullConnectUser(curr,GlobalGoners);
383                                 continue;
384                         }
385
386                         // It's time to PING this user. Send them a ping.
387                         if ((TIME > curr->nping) && (curr->registered == 7))
388                         {
389                                 // This user didn't answer the last ping, remove them
390                                 if (!curr->lastping)
391                                 {
392                                         GlobalGoners->AddItem(curr,"Ping timeout");
393                                         continue;
394                                 }
395
396                                 Write(curr->fd,"PING :%s",Config->ServerName);
397                                 curr->lastping = 0;
398                                 curr->nping = TIME+curr->pingmax;
399                         }
400
401                         /*
402                          * We can flush the write buffer as the last thing we do, because if they
403                          * match any of the above conditions its no use flushing their buffer anyway.
404                          */
405                         curr->FlushWriteBuf();
406
407                         if (curr->GetWriteError() != "")
408                         {
409                                 GlobalGoners->AddItem(curr,curr->GetWriteError());
410                                 continue;
411                         }
412                 }
413         }
414
415         /* Remove all the queued users who are due to be quit, free memory used. */
416         GlobalGoners->Apply();
417         delete GlobalGoners;
418         return;
419 }
420
421 void OpenLog(char** argv, int argc)
422 {
423         if (!*LOG_FILE)
424         {
425                 if (Config->logpath == "")
426                 {
427                         Config->logpath = GetFullProgDir(argv,argc) + "/ircd.log";
428                 }
429         }
430         else
431         {
432                 Config->log_file = fopen(LOG_FILE,"a+");
433
434                 if (!Config->log_file)
435                 {
436                         printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
437                         Exit(ERROR);
438                 }
439
440                 return;
441         }
442
443         Config->log_file = fopen(Config->logpath.c_str(),"a+");
444
445         if (!Config->log_file)
446         {
447                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",Config->logpath.c_str());
448                 Exit(ERROR);
449         }
450 }
451
452
453 void CheckRoot()
454 {
455         if (geteuid() == 0)
456         {
457                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
458                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
459                 Exit(ERROR);
460         }
461 }
462
463
464 void CheckDie()
465 {
466         if (*Config->DieValue)
467         {
468                 printf("WARNING: %s\n\n",Config->DieValue);
469                 log(DEFAULT,"Uh-Oh, somebody didn't read their config file: '%s'",Config->DieValue);
470                 Exit(ERROR);
471         }
472 }
473
474 /* We must load the modules AFTER initializing the socket engine, now */
475 void LoadAllModules(InspIRCd* ServerInstance)
476 {
477         char configToken[MAXBUF];
478
479         MODCOUNT = -1;
480
481         for (int count = 0; count < Config->ConfValueEnum("module",&Config->config_f); count++)
482         {
483                 Config->ConfValue("module","name",count,configToken,&Config->config_f);
484                 printf("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
485
486                 if (!ServerInstance->LoadModule(configToken))
487                 {
488                         log(DEFAULT,"Exiting due to a module loader error.");
489                         printf("\nThere was an error loading a module: %s\n\n",ServerInstance->ModuleError());
490                         Exit(0);
491                 }
492         }
493
494         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
495 }
496
497