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