]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/userprocess.cpp
Use our shiny new IS_LOCAL() macro, and add a query.
[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
61 extern int MODCOUNT;
62 extern int openSockfd[MAXSOCKS];
63 extern bool nofork;
64 extern bool unlimitcore;
65 extern struct sockaddr_in client,server;
66 extern char addrs[MAXBUF][255];
67 extern socklen_t length;
68 extern char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
69
70 extern char DisabledCommands[MAXBUF];
71
72 extern bool AllowHalfop;
73 extern bool AllowProtect;
74 extern bool AllowFounder;
75
76 extern std::vector<Module*> modules;
77 extern std::vector<std::string> module_names;
78 extern std::vector<ircd_module*> factory;
79
80 extern std::vector<InspSocket*> module_sockets;
81
82 extern SocketEngine* SE;
83
84 extern time_t TIME;
85 extern time_t OLDTIME;
86
87 extern int DieDelay;
88 extern time_t startup_time;
89 extern int NetBufferSize;
90 extern int MaxConn;
91 extern unsigned int SoftLimit;
92 extern int MaxWhoResults;
93 extern time_t nb_start;
94 extern int dns_timeout;
95
96 extern int statsAccept, statsRefused, statsUnknown, statsCollisions, statsDns, statsDnsGood, statsDnsBad, statsConnects, statsSent, statsRecv;
97
98 extern userrec* fd_ref_table[65536];
99
100 extern int LogLevel;
101 extern char ServerName[MAXBUF];
102 extern char Network[MAXBUF];
103 extern char ServerDesc[MAXBUF];
104 extern char AdminName[MAXBUF];
105 extern char AdminEmail[MAXBUF];
106 extern char AdminNick[MAXBUF];
107 extern char diepass[MAXBUF];
108 extern char restartpass[MAXBUF];
109 extern char motd[MAXBUF];
110 extern char rules[MAXBUF];
111 extern char list[MAXBUF];
112 extern char PrefixQuit[MAXBUF];
113 extern char DieValue[MAXBUF];
114 extern char DNSServer[MAXBUF];
115 extern char data[65536];
116
117
118 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
119 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
120 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
121 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
122
123 extern user_hash clientlist;
124 extern chan_hash chanlist;
125 extern whowas_hash whowas;
126
127 extern FILE *log_file;
128 extern std::stringstream config_f;
129
130 void ProcessUser(userrec* cu)
131 {
132         int result = EAGAIN;
133         log(DEBUG,"Processing user with fd %d",cu->fd);
134         int MOD_RESULT = 0;
135         int result2 = 0;
136         FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
137         if (!MOD_RESULT)
138         {
139                 result = cu->ReadData(data, 65535);
140         }
141         else
142         {
143                 log(DEBUG,"Data result returned by module: %d",MOD_RESULT);
144                 result = result2;
145         }
146         log(DEBUG,"Read result: %d",result);
147         if (result)
148         {
149                 statsRecv += result;
150                 // perform a check on the raw buffer as an array (not a string!) to remove
151                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
152                 // hopefully this should stop even more people whining about "Unknown command: *"
153                 for (int checker = 0; checker < result; checker++)
154                 {
155                         if ((data[checker] == 0) || (data[checker] == 7))
156                                 data[checker] = ' ';
157                 }
158                 if (result > 0)
159                         data[result] = '\0';
160                 userrec* current = cu;
161                 int currfd = current->fd;
162                 int floodlines = 0;
163                 // add the data to the users buffer
164                 if (result > 0)
165                 {
166                         if (!current->AddBuffer(data))
167                         {
168                                 // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
169                                 if (current->registered == 7)
170                                 {
171                                         kill_link(current,"RecvQ exceeded");
172                                 }
173                                 else
174                                 {
175                                         WriteOpers("*** Excess flood from %s",current->ip);
176                                         log(DEFAULT,"Excess flood from: %s",current->ip);
177                                         add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
178                                         apply_lines();
179                                 }
180                                 return;
181                         }
182                         if (current->recvq.length() > (unsigned)NetBufferSize)
183                         {
184                                 if (current->registered == 7)
185                                 {
186                                         kill_link(current,"RecvQ exceeded");
187                                 }
188                                 else
189                                 {
190                                         WriteOpers("*** Excess flood from %s",current->ip);
191                                         log(DEFAULT,"Excess flood from: %s",current->ip);
192                                         add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
193                                         apply_lines();
194                                 }
195                                 return;
196                         }
197                         // while there are complete lines to process...
198                         while (current->BufferIsReady())
199                         {
200                                 floodlines++;
201                                 if (TIME > current->reset_due)
202                                 {
203                                         current->reset_due = TIME + current->threshold;
204                                         current->lines_in = 0;
205                                 }
206                                 current->lines_in++;
207                                 if (current->lines_in > current->flood)
208                                 {
209                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
210                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
211                                         kill_link(current,"Excess flood");
212                                         return;
213                                 }
214                                 if ((floodlines > current->flood) && (current->flood != 0))
215                                 {
216                                         if (current->registered == 7)
217                                         {
218                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
219                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
220                                                 kill_link(current,"Excess flood");
221                                         }
222                                         else
223                                         {
224                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
225                                                 apply_lines();
226                                         }
227                                         return;
228                                 }
229                                 char sanitized[MAXBUF];
230                                 // use GetBuffer to copy single lines into the sanitized string
231                                 std::string single_line = current->GetBuffer();
232                                 current->bytes_in += single_line.length();
233                                 current->cmds_in++;
234                                 if (single_line.length()>512)
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                                 strlcpy(sanitized,single_line.c_str(),MAXBUF);
242                                 if (*sanitized)
243                                 {
244                                         userrec* old_comp = fd_ref_table[currfd];
245                                         // we're gonna re-scan to check if the nick is gone, after every
246                                         // command - if it has, we're gonna bail
247                                         process_buffer(sanitized,current);
248                                         // look for the user's record in case it's changed... if theyve quit,
249                                         // we cant do anything more with their buffer, so bail.
250                                         // there used to be an ugly, slow loop here. Now we have a reference
251                                         // table, life is much easier (and FASTER)
252                                         userrec* new_comp = fd_ref_table[currfd];
253                                         if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
254                                         {
255                                                 return;
256                                         }
257                                         else
258                                         {
259                                                 /* The user is still here, flush their buffer */
260                                                 current->FlushWriteBuf();
261                                         }
262                                 }
263                         }
264                         return;
265                 }
266                 if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
267                 {
268                         log(DEBUG,"killing: %s",cu->nick);
269                         kill_link(cu,strerror(errno));
270                         return;
271                 }
272         }
273         // result EAGAIN means nothing read
274         else if (result == EAGAIN)
275         {
276         }
277         else if (result == 0)
278         {
279                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
280                 kill_link(cu,"Client exited");
281                 log(DEBUG,"Bailing from client exit");
282                 return;
283         }
284 }
285
286
287 /**
288  * This function is called once a second from the mainloop.
289  * It is intended to do background checking on all the user structs, e.g.
290  * stuff like ping checks, registration timeouts, etc.
291  * The function returns false when it is finished, and true if
292  * it needs to be run again (e.g. it has processed one of a batch of
293  * QUIT messages, but couldnt continue iterating because the iterator
294  * became invalid). This function is also responsible for checking
295  * if InspSocket derived classes are timed out.
296  */
297 bool DoBackgroundUserStuff(time_t TIME)
298 {
299         unsigned int numsockets = module_sockets.size();
300         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
301         {
302                 InspSocket* s = (InspSocket*)*a;
303                 if (s->Timeout(TIME))
304                 {
305                         log(DEBUG,"Socket poll returned false, close and bail");
306                         SE->DelFd(s->GetFd());
307                         s->Close();
308                         module_sockets.erase(a);
309                         delete s;
310                         break;
311                 }
312                 if (module_sockets.size() != numsockets) break;
313         }
314         /* TODO: We need a seperate hash containing only local users for this
315          */
316         for (user_hash::iterator count2 = clientlist.begin(); count2 != clientlist.end(); count2++)
317         {
318                 /* Sanity checks for corrupted iterators (yes, really) */
319                 userrec* curr = NULL;
320                 if (count2->second)
321                         curr = count2->second;
322                 if ((long)curr == -1)
323                         return false;
324
325                 if ((curr) && (curr->fd != 0)) /* XXX - why are we checking fd != 0? --w00t */
326                 {
327                         int currfd = curr->fd;
328                         // we don't check the state of remote users.
329                         if (IS_LOCAL(curr))
330                         {
331                                 curr->FlushWriteBuf();
332                                 if (curr->GetWriteError() != "")
333                                 {
334                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
335                                         kill_link(curr,curr->GetWriteError().c_str());
336                                         return true;
337                                 }
338                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
339                                 // their connection class.
340                                 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
341                                 {
342                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
343                                         kill_link(curr,"Registration timeout");
344                                         return true;
345                                 }
346                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
347                                 {
348                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
349                                         curr->dns_done = true;
350                                         statsDnsBad++;
351                                         FullConnectUser(curr);
352                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
353                                                 return true;
354                                  }
355                                  if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
356                                  {
357                                        log(DEBUG,"dns done, registered=3, and modules ready, OK");
358                                        FullConnectUser(curr);
359                                        if (fd_ref_table[currfd] != curr) // something changed, bail pronto
360                                                 return true;
361                                  }
362                                  if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
363                                  {
364                                        if ((!curr->lastping) && (curr->registered == 7))
365                                        {
366                                                log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
367                                                kill_link(curr,"Ping timeout");
368                                                return true;
369                                        }
370                                        Write(curr->fd,"PING :%s",ServerName);
371                                        log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
372                                        curr->lastping = 0;
373                                        curr->nping = TIME+curr->pingmax;       // was hard coded to 120
374                                 }
375                         }
376                 }
377         }
378         return false;
379 }
380
381 void OpenLog(char** argv, int argc)
382 {
383         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
384         log_file = fopen(logpath.c_str(),"a+");
385         if (!log_file)
386         {
387                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
388                 Exit(ERROR);
389         }
390 #ifdef IS_CYGWIN
391         printf("Logging to ircd.log...\n");
392 #else
393         printf("Logging to %s...\n",logpath.c_str());
394 #endif
395 }
396
397
398 void CheckRoot()
399 {
400         if (geteuid() == 0)
401         {
402                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
403                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
404                 Exit(ERROR);
405         }
406 }
407
408
409 void CheckDie()
410 {
411         if (DieValue[0])
412         {
413                 printf("WARNING: %s\n\n",DieValue);
414                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
415                 exit(0);
416         }
417 }
418
419 void LoadAllModules()
420 {
421         /* We must load the modules AFTER initializing the socket engine, now */
422         MODCOUNT = -1;
423         for (int count = 0; count < ConfValueEnum("module",&config_f); count++)
424         {
425                 ConfValue("module","name",count,configToken,&config_f);
426                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
427                 if (!LoadModule(configToken))
428                 {
429                         log(DEFAULT,"Exiting due to a module loader error.");
430                         printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
431                         Exit(0);
432                 }
433         }
434         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
435 }
436
437