]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/userprocess.cpp
c4541c29a31f712af4f3e2d06777ff2b573137ff
[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 #include "command_parse.h"
61 #include "cull_list.h"
62
63 extern int MODCOUNT;
64 extern struct sockaddr_in client,server;
65 extern socklen_t length;
66 extern std::vector<Module*> modules;
67 extern std::vector<ircd_module*> factory;
68 extern std::vector<InspSocket*> module_sockets;
69 extern time_t TIME;
70 extern time_t OLDTIME;
71 extern std::vector<userrec*> local_users;
72
73 extern InspIRCd* ServerInstance;
74 extern ServerConfig *Config;
75 extern userrec* fd_ref_table[65536];
76 char data[65536];
77
78 extern user_hash clientlist;
79 extern chan_hash chanlist;
80
81 void ProcessUser(userrec* cu)
82 {
83         int result = EAGAIN;
84         if (cu->fd == FD_MAGIC_NUMBER)
85                 return;
86         log(DEBUG,"Processing user with fd %d",cu->fd);
87         if (Config->GetIOHook(cu->port))
88         {
89                 int result2 = 0;
90                 int MOD_RESULT = Config->GetIOHook(cu->port)->OnRawSocketRead(cu->fd,data,65535,result2);
91                 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
92                 if (MOD_RESULT < 0)
93                 {
94                         result = EAGAIN;
95                 }
96                 else
97                 {
98                         result = result2;
99                 }
100         }
101         else
102         {
103                 result = cu->ReadData(data, 65535);
104         }
105         log(DEBUG,"Read result: %d",result);
106         if (result)
107         {
108                 ServerInstance->stats->statsRecv += result;
109                 // perform a check on the raw buffer as an array (not a string!) to remove
110                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
111                 // hopefully this should stop even more people whining about "Unknown command: *"
112                 for (int checker = 0; checker < result; checker++)
113                 {
114                         if ((data[checker] == 0) || (data[checker] == 7))
115                                 data[checker] = ' ';
116                 }
117                 if (result > 0)
118                         data[result] = '\0';
119                 userrec* current = cu;
120                 int currfd = current->fd;
121                 int floodlines = 0;
122                 // add the data to the users buffer
123                 if (result > 0)
124                 {
125                         if (!current->AddBuffer(data))
126                         {
127                                 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
128                                 if (current->registered == 7)
129                                 {
130                                         kill_link(current,"RecvQ exceeded");
131                                 }
132                                 else
133                                 {
134                                         WriteOpers("*** Excess flood from %s",current->ip);
135                                         log(DEFAULT,"Excess flood from: %s",current->ip);
136                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
137                                         apply_lines(APPLY_ZLINES);
138                                 }
139                                 return;
140                         }
141                         if (current->recvq.length() > (unsigned)Config->NetBufferSize)
142                         {
143                                 if (current->registered == 7)
144                                 {
145                                         kill_link(current,"RecvQ exceeded");
146                                 }
147                                 else
148                                 {
149                                         WriteOpers("*** Excess flood from %s",current->ip);
150                                         log(DEFAULT,"Excess flood from: %s",current->ip);
151                                         add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
152                                         apply_lines(APPLY_ZLINES);
153                                 }
154                                 return;
155                         }
156                         // while there are complete lines to process...
157                         while (current->BufferIsReady())
158                         {
159                                 floodlines++;
160                                 if (TIME > current->reset_due)
161                                 {
162                                         current->reset_due = TIME + current->threshold;
163                                         current->lines_in = 0;
164                                 }
165                                 current->lines_in++;
166                                 if (current->lines_in > current->flood)
167                                 {
168                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
169                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
170                                         kill_link(current,"Excess flood");
171                                         return;
172                                 }
173                                 if ((floodlines > current->flood) && (current->flood != 0))
174                                 {
175                                         if (current->registered == 7)
176                                         {
177                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
178                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
179                                                 kill_link(current,"Excess flood");
180                                         }
181                                         else
182                                         {
183                                                 add_zline(120,Config->ServerName,"Flood from unregistered connection",current->ip);
184                                                 apply_lines(APPLY_ZLINES);
185                                         }
186                                         return;
187                                 }
188                                 char sanitized[MAXBUF];
189                                 // use GetBuffer to copy single lines into the sanitized string
190                                 std::string single_line = current->GetBuffer();
191                                 current->bytes_in += single_line.length();
192                                 current->cmds_in++;
193                                 if (single_line.length()>512)
194                                 {
195                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
196                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
197                                         kill_link(current,"Excess flood");
198                                         return;
199                                 }
200                                 strlcpy(sanitized,single_line.c_str(),MAXBUF);
201                                 if (*sanitized)
202                                 {
203                                         userrec* old_comp = fd_ref_table[currfd];
204                                         // we're gonna re-scan to check if the nick is gone, after every
205                                         // command - if it has, we're gonna bail
206                                         ServerInstance->Parser->ProcessBuffer(sanitized,current);
207                                         // look for the user's record in case it's changed... if theyve quit,
208                                         // we cant do anything more with their buffer, so bail.
209                                         // there used to be an ugly, slow loop here. Now we have a reference
210                                         // table, life is much easier (and FASTER)
211                                         userrec* new_comp = fd_ref_table[currfd];
212                                         if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
213                                         {
214                                                 return;
215                                         }
216                                         else
217                                         {
218                                                 /* The user is still here, flush their buffer */
219                                                 current->FlushWriteBuf();
220                                         }
221                                 }
222                         }
223                         return;
224                 }
225                 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
226                 {
227                         log(DEBUG,"killing: %s",cu->nick);
228                         kill_link(cu,strerror(errno));
229                         return;
230                 }
231         }
232         // result EAGAIN means nothing read
233         else if (result == EAGAIN)
234         {
235         }
236         else if (result == 0)
237         {
238                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
239                 kill_link(cu,"Client exited");
240                 log(DEBUG,"Bailing from client exit");
241                 return;
242         }
243 }
244
245 /**
246  * This function is called once a second from the mainloop.
247  * It is intended to do background checking on all the user structs, e.g.
248  * stuff like ping checks, registration timeouts, etc.
249  * The function returns false when it is finished, and true if
250  * it needs to be run again (e.g. it has processed one of a batch of
251  * QUIT messages, but couldnt continue iterating because the iterator
252  * became invalid). This function is also responsible for checking
253  * if InspSocket derived classes are timed out.
254  */
255 bool DoBackgroundUserStuff(time_t TIME)
256 {
257         unsigned int numsockets = module_sockets.size();
258         SocketEngine* SE = ServerInstance->SE;
259         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
260         {
261                 InspSocket* s = (InspSocket*)*a;
262                 if (s->Timeout(TIME))
263                 {
264                         log(DEBUG,"Socket poll returned false, close and bail");
265                         SE->DelFd(s->GetFd());
266                         s->Close();
267                         module_sockets.erase(a);
268                         delete s;
269                         break;
270                 }
271                 if (module_sockets.size() != numsockets) break;
272         }
273         CullList* GlobalGoners = new CullList();
274         for (std::vector<userrec*>::iterator count2 = local_users.begin(); count2 != local_users.end(); count2++)
275         {
276                 /* Sanity checks for corrupted iterators (yes, really) */
277                 userrec* curr = NULL;
278                 if (*count2)
279                         curr = (userrec*)(*count2);
280                 if ((long)curr == -1)
281                         return false;
282
283                 if (curr)
284                 {
285                         // registration timeout -- didnt send USER/NICK/HOST in the time specified in
286                         // their connection class.
287                         if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
288                         {
289                                 log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
290                                 GlobalGoners->AddItem(curr,"Registration timeout");
291                                 continue;
292                         }
293                         // user has signed on with USER/NICK/PASS, and dns has completed, all the modules
294                         // say this user is ok to proceed, fully connect them.
295                         if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
296                         {
297                                 curr->dns_done = true;
298                                 ServerInstance->stats->statsDnsBad++;
299                                 FullConnectUser(curr,GlobalGoners);
300                                 continue;
301                         }
302                         if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
303                         {
304                                 log(DEBUG,"dns done, registered=3, and modules ready, OK");
305                                 FullConnectUser(curr,GlobalGoners);
306                                 continue;
307                         }
308                         // It's time to PING this user. Send them a ping.
309                         // XXX: We were checking isnick() here -- why when we check curr->registered? - Brain
310                         if ((TIME > curr->nping) && (curr->registered == 7))
311                         {
312                                 // This user didn't answer the last ping, remove them
313                                 if (!curr->lastping)
314                                 {
315                                         GlobalGoners->AddItem(curr,"Ping timeout");
316                                         continue;
317                                 }
318                                 Write(curr->fd,"PING :%s",Config->ServerName);
319                                 curr->lastping = 0;
320                                 curr->nping = TIME+curr->pingmax;
321                         }
322                         // XXX: We can flush the write buffer as the last thing we do, because if they
323                         // match any of the above conditions its no use flushing their buffer anyway.
324                         curr->FlushWriteBuf();
325                         if (curr->GetWriteError() != "")
326                         {
327                                 GlobalGoners->AddItem(curr,curr->GetWriteError());
328                                 continue;
329                         }
330                 }
331         }
332         /** Remove all the queued users who are due to be quit
333          */
334         GlobalGoners->Apply();
335         /** Free to memory used
336          */
337         delete GlobalGoners;
338         /** XXX: The old system prior to 1.0RC2 would call this function
339          * repeatedly until everything was ship-shape, however now we are
340          * using CullList to avoid bailing from the loop, so this is no
341          * longer required. We always return false here so this only executes
342          * once. At some future date the while loop may be removed from
343          * the mainloop which calls this function.
344          */
345         return false;
346 }
347
348 void OpenLog(char** argv, int argc)
349 {
350         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
351         Config->log_file = fopen(logpath.c_str(),"a+");
352         if (!Config->log_file)
353         {
354                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
355                 Exit(ERROR);
356         }
357 #ifdef IS_CYGWIN
358         printf("Logging to ircd.log...\n");
359 #else
360         printf("Logging to %s...\n",logpath.c_str());
361 #endif
362 }
363
364
365 void CheckRoot()
366 {
367         if (geteuid() == 0)
368         {
369                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
370                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
371                 Exit(ERROR);
372         }
373 }
374
375
376 void CheckDie()
377 {
378         if (*Config->DieValue)
379         {
380                 printf("WARNING: %s\n\n",Config->DieValue);
381                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",Config->DieValue);
382                 exit(0);
383         }
384 }
385
386 void LoadAllModules(InspIRCd* ServerInstance)
387 {
388         /* We must load the modules AFTER initializing the socket engine, now */
389         MODCOUNT = -1;
390         char configToken[MAXBUF];
391         for (int count = 0; count < Config->ConfValueEnum("module",&Config->config_f); count++)
392         {
393                 Config->ConfValue("module","name",count,configToken,&Config->config_f);
394                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
395                 if (!ServerInstance->LoadModule(configToken))
396                 {
397                         log(DEFAULT,"Exiting due to a module loader error.");
398                         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());
399                         Exit(0);
400                 }
401         }
402         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
403 }
404
405