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