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