Author: Bleep <tomh@inxpress.net>
[ircu2.10.12-pk.git] / ircd / s_misc.c
1 /*
2  * IRC - Internet Relay Chat, ircd/s_misc.c (formerly ircd/date.c)
3  * Copyright (C) 1990 Jarkko Oikarinen and
4  *                    University of Oulu, Computing Center
5  *
6  * See file AUTHORS in IRC package for additional names of
7  * the programmers.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 1, or (at your option)
12  * any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  * $Id$
24  */
25 #include "s_misc.h"
26 #include "IPcheck.h"
27 #include "channel.h"
28 #include "client.h"
29 #include "hash.h"
30 #include "ircd.h"
31 #include "ircd_alloc.h"
32 #include "ircd_log.h"
33 #include "ircd_string.h"
34 #include "list.h"
35 #include "match.h"
36 #include "msg.h"
37 #include "numeric.h"
38 #include "numnicks.h"
39 #include "parse.h"
40 #include "querycmds.h"
41 #include "res.h"
42 #include "s_bsd.h"
43 #include "s_conf.h"
44 #include "s_debug.h"
45 #include "s_user.h"
46 #include "send.h"
47 #include "sprintf_irc.h"
48 #include "struct.h"
49 #include "support.h"
50 #include "sys.h"
51 #include "userload.h"
52
53 #include <assert.h>
54 #include <fcntl.h>
55 #include <netdb.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <sys/stat.h>
59 #include <unistd.h>
60
61 static void exit_one_client(struct Client *, char *);
62
63 static char *months[] = {
64   "January", "February", "March", "April",
65   "May", "June", "July", "August",
66   "September", "October", "November", "December"
67 };
68
69 static char *weekdays[] = {
70   "Sunday", "Monday", "Tuesday", "Wednesday",
71   "Thursday", "Friday", "Saturday"
72 };
73
74 /*
75  * stats stuff
76  */
77 static struct ServerStatistics ircst;
78 struct ServerStatistics* ServerStats = &ircst;
79
80 char *date(time_t clock)
81 {
82   static char buf[80], plus;
83   struct tm *lt, *gm;
84   struct tm gmbuf;
85   int minswest;
86
87   if (!clock)
88     clock = CurrentTime;
89   gm = gmtime(&clock);
90   memcpy(&gmbuf, gm, sizeof(gmbuf));
91   gm = &gmbuf;
92   lt = localtime(&clock);
93
94   minswest = (gm->tm_hour - lt->tm_hour) * 60 + (gm->tm_min - lt->tm_min);
95   if (lt->tm_yday != gm->tm_yday)
96   {
97     if ((lt->tm_yday > gm->tm_yday && lt->tm_year == gm->tm_year) ||
98         (lt->tm_yday < gm->tm_yday && lt->tm_year != gm->tm_year))
99       minswest -= 24 * 60;
100     else
101       minswest += 24 * 60;
102   }
103
104   plus = (minswest > 0) ? '-' : '+';
105   if (minswest < 0)
106     minswest = -minswest;
107
108   sprintf(buf, "%s %s %d %d -- %02d:%02d %c%02d:%02d",
109       weekdays[lt->tm_wday], months[lt->tm_mon], lt->tm_mday,
110       1900 + lt->tm_year, lt->tm_hour, lt->tm_min,
111       plus, minswest / 60, minswest % 60);
112
113   return buf;
114 }
115
116 /*
117  * myctime
118  *
119  * This is like standard ctime()-function, but it zaps away
120  * the newline from the end of that string. Also, it takes
121  * the time value as parameter, instead of pointer to it.
122  * Note that it is necessary to copy the string to alternate
123  * buffer (who knows how ctime() implements it, maybe it statically
124  * has newline there and never 'refreshes' it -- zapping that
125  * might break things in other places...)
126  */
127 char *myctime(time_t value)
128 {
129   static char buf[28];
130   char *p;
131
132   strcpy(buf, ctime(&value));
133   if ((p = strchr(buf, '\n')) != NULL)
134     *p = '\0';
135
136   return buf;
137 }
138
139 /*
140  *  get_client_name
141  *       Return the name of the client for various tracking and
142  *       admin purposes. The main purpose of this function is to
143  *       return the "socket host" name of the client, if that
144  *    differs from the advertised name (other than case).
145  *    But, this can be used to any client structure.
146  *
147  *    Returns:
148  *      "name[user@ip#.port]" if 'showip' is true;
149  *      "name[sockethost]", if name and sockhost are different and
150  *      showip is false; else
151  *      "name".
152  *
153  *  NOTE 1:
154  *    Watch out the allocation of "nbuf", if either sptr->name
155  *    or sptr->sockhost gets changed into pointers instead of
156  *    directly allocated within the structure...
157  *
158  *  NOTE 2:
159  *    Function return either a pointer to the structure (sptr) or
160  *    to internal buffer (nbuf). *NEVER* use the returned pointer
161  *    to modify what it points!!!
162  */
163 const char* get_client_name(const struct Client* sptr, int showip)
164 {
165   static char nbuf[HOSTLEN * 2 + USERLEN + 5];
166
167   if (MyConnect(sptr)) {
168     if (showip)
169       sprintf_irc(nbuf, "%s[%s@%s]", sptr->name,
170             (IsIdented(sptr)) ? sptr->username : "", sptr->sock_ip);
171     else {
172       if (0 != ircd_strcmp(sptr->name, sptr->sockhost))
173         sprintf_irc(nbuf, "%s[%s]", sptr->name, sptr->sockhost);
174       else
175         return sptr->name;
176     }
177     return nbuf;
178   }
179   return sptr->name;
180 }
181
182 const char *get_client_host(const struct Client *cptr)
183 {
184   return get_client_name(cptr, HIDE_IP);
185 }
186
187 /*
188  * Form sockhost such that if the host is of form user@host, only the host
189  * portion is copied.
190  */
191 void get_sockhost(struct Client *cptr, char *host)
192 {
193   char *s;
194   if ((s = strchr(host, '@')))
195     s++;
196   else
197     s = host;
198   ircd_strncpy(cptr->sockhost, s, HOSTLEN);
199 }
200
201 /*
202  * exit_downlinks - added by Run 25-9-94
203  *
204  * Removes all clients and downlinks (+clients) of any server
205  * QUITs are generated and sent to local users.
206  *
207  * cptr    : server that must have all dependents removed
208  * sptr    : source who thought that this was a good idea
209  * comment : comment sent as sign off message to local clients
210  */
211 static void exit_downlinks(struct Client *cptr, struct Client *sptr, char *comment)
212 {
213   struct Client *acptr;
214   struct DLink *next;
215   struct DLink *lp;
216   struct Client **acptrp;
217   int i;
218
219   /* Run over all its downlinks */
220   for (lp = cptr->serv->down; lp; lp = next)
221   {
222     next = lp->next;
223     acptr = lp->value.cptr;
224     /* Remove the downlinks and client of the downlink */
225     exit_downlinks(acptr, sptr, comment);
226     /* Remove the downlink itself */
227     exit_one_client(acptr, me.name);
228   }
229   /* Remove all clients of this server */
230   acptrp = cptr->serv->client_list;
231   for (i = 0; i <= cptr->serv->nn_mask; ++acptrp, ++i) {
232     if (*acptrp)
233       exit_one_client(*acptrp, comment);
234   }
235 }
236
237 /*
238  * exit_client, rewritten 25-9-94 by Run
239  *
240  * This function exits a client of *any* type (user, server, etc)
241  * from this server. Also, this generates all necessary prototol
242  * messages that this exit may cause.
243  *
244  * This function implicitly exits all other clients depending on
245  * this connection.
246  *
247  * For convenience, this function returns a suitable value for
248  * m_funtion return value:
249  *
250  *   CPTR_KILLED     if (cptr == bcptr)
251  *   0                if (cptr != bcptr)
252  *
253  * This function can be called in two ways:
254  * 1) From before or in parse(), exitting the 'cptr', in which case it was
255  *    invoked as exit_client(cptr, cptr, &me,...), causing it to always
256  *    return CPTR_KILLED.
257  * 2) Via parse from a m_function call, in which case it was invoked as
258  *    exit_client(cptr, acptr, sptr, ...). Here 'sptr' is known; the client
259  *    that generated the message in a way that we can assume he already
260  *    did remove acptr from memory himself (or in other cases we don't mind
261  *    because he will be delinked.) Or invoked as:
262  *    exit_client(cptr, acptr/sptr, &me, ...) when WE decide this one should
263  *    be removed.
264  * In general: No generated SQUIT or QUIT should be sent to source link
265  * sptr->from. And CPTR_KILLED should be returned if cptr got removed (too).
266  *
267  * --Run
268  */
269 int exit_client(struct Client *cptr,    /* Connection being handled by
270                                    read_message right now */
271     struct Client* victim,              /* Client being killed */
272     struct Client* killer,              /* The client that made the decision
273                                    to remove this one, never NULL */
274     char *comment)              /* Reason for the exit */
275 {
276   struct Client* acptr = 0;
277   struct DLink *dlp;
278 #ifdef  FNAME_USERLOG
279   time_t on_for;
280 #endif
281   char comment1[HOSTLEN + HOSTLEN + 2];
282
283   if (MyConnect(victim)) {
284     victim->flags |= FLAGS_CLOSING;
285 #ifdef ALLOW_SNO_CONNEXIT
286 #ifdef SNO_CONNEXIT_IP
287     if (IsUser(victim)) {
288       sprintf_irc(sendbuf,
289           ":%s NOTICE * :*** Notice -- Client exiting: %s (%s@%s) [%s] [%s]",
290           me.name, victim->name, victim->user->username, victim->user->host,
291           comment, ircd_ntoa((const char*) &victim->ip));
292       sendbufto_op_mask(SNO_CONNEXIT);
293     }
294 #else /* SNO_CONNEXIT_IP */
295     if (IsUser(victim)) {
296       sprintf_irc(sendbuf,
297           ":%s NOTICE * :*** Notice -- Client exiting: %s (%s@%s) [%s]",
298           me.name, victim->name, victim->user->username, victim->user->host,
299           comment);
300       sendbufto_op_mask(SNO_CONNEXIT);
301     }
302 #endif /* SNO_CONNEXIT_IP */
303 #endif /* ALLOW_SNO_CONNEXIT */
304     update_load();
305 #ifdef FNAME_USERLOG
306     on_for = CurrentTime - victim->firsttime;
307 #if defined(USE_SYSLOG) && defined(SYSLOG_USERS)
308     if (IsUser(victim))
309       ircd_log(L_TRACE, "%s (%3d:%02d:%02d): %s@%s (%s)\n",
310                myctime(victim->firsttime), on_for / 3600, (on_for % 3600) / 60,
311                on_for % 60, victim->user->username, victim->sockhost, victim->name);
312 #else
313     if (IsUser(victim))
314       write_log(FNAME_USERLOG,
315                "%s (%3d:%02d:%02d): %s@%s [%s]\n",
316                myctime(victim->firsttime),
317                on_for / 3600, (on_for % 3600) / 60,
318                on_for % 60,
319                victim->user->username, victim->user->host, victim->username);
320 #endif
321 #endif
322     if (victim != killer->from  /* The source knows already */
323         && IsClient(victim))    /* Not a Ping struct or Log file */
324     {
325       if (IsServer(victim) || IsHandshake(victim))
326         sendto_one(victim, ":%s SQUIT %s 0 :%s", killer->name, me.name, comment);
327       else if (!IsConnecting(victim)) {
328         if (!IsDead(victim))
329           sendto_one(victim, "ERROR :Closing Link: %s by %s (%s)",
330                      victim->name, killer->name, comment);
331       }
332       if ((IsServer(victim) || IsHandshake(victim) || IsConnecting(victim)) &&
333           (killer == &me || (IsServer(killer) &&
334           (strncmp(comment, "Leaf-only link", 14) ||
335           strncmp(comment, "Non-Hub link", 12)))))
336       {
337         /*
338          * Note: check user == user needed to make sure we have the same
339          * client
340          */
341         if (victim->serv->user && *victim->serv->by &&
342             (acptr = findNUser(victim->serv->by))) {
343           if (acptr->user == victim->serv->user) {
344             if (MyUser(acptr) || Protocol(acptr->from) < 10)
345               sendto_one(acptr,
346                          ":%s NOTICE %s :Link with %s cancelled: %s",
347                          me.name, acptr->name, victim->name, comment);
348             else
349               sendto_one(acptr,
350                          "%s NOTICE %s%s :Link with %s cancelled: %s",
351                          NumServ(&me), NumNick(acptr), victim->name, comment);
352           }
353           else {
354             /*
355              * not right client, set by to empty string
356              */
357             acptr = 0;
358             *victim->serv->by = '\0';
359           }
360         }
361         if (killer == &me)
362           sendto_lops_butone(acptr, "Link with %s cancelled: %s",
363                              victim->name, comment);
364       }
365     }
366     /*
367      *  Close the Client connection first.
368      */
369     close_connection(victim);
370   }
371
372   if (IsServer(victim))
373   {
374     strcpy(comment1, victim->serv->up->name);
375     strcat(comment1, " ");
376     strcat(comment1, victim->name);
377     if (IsUser(killer))
378       sendto_lops_butone(killer, "%s SQUIT by %s [%s]:",
379                          (killer->user->server == victim ||
380                          killer->user->server == victim->serv->up) ? "Local" : "Remote",
381                          get_client_name(killer, HIDE_IP), killer->user->server->name);
382     else if (killer != &me && victim->serv->up != killer)
383       sendto_ops("Received SQUIT %s from %s :", victim->name,
384                  IsServer(killer) ? killer->name : get_client_name(killer, HIDE_IP));
385     sendto_op_mask(SNO_NETWORK, "Net break: %s (%s)", comment1, comment);
386   }
387
388   /*
389    * First generate the needed protocol for the other server links
390    * except the source:
391    */
392   for (dlp = me.serv->down; dlp; dlp = dlp->next) {
393     if (dlp->value.cptr != killer->from && dlp->value.cptr != victim) {
394       if (IsServer(victim))
395         sendto_one(dlp->value.cptr, ":%s SQUIT %s " TIME_T_FMT " :%s",
396                    killer->name, victim->name, victim->serv->timestamp, comment);
397       else if (IsUser(victim) && 0 == (victim->flags & FLAGS_KILLED))
398         sendto_one(dlp->value.cptr, "%s%s " TOK_QUIT " :%s", NumNick(victim), comment);
399     }
400   }
401   /* Then remove the client structures */
402   if (IsServer(victim))
403     exit_downlinks(victim, killer, comment1);
404   exit_one_client(victim, comment);
405
406   /*
407    *  cptr can only have been killed if it was cptr itself that got killed here,
408    *  because cptr can never have been a dependant of victim    --Run
409    */
410   return (cptr == victim) ? CPTR_KILLED : 0;
411 }
412
413 /*
414  * Exit client with formatted message, added 25-9-94 by Run
415  */
416 int vexit_client_msg(struct Client *cptr, struct Client *bcptr, struct Client *sptr,
417     char *pattern, va_list vl)
418 {
419   char msgbuf[1024];
420   vsprintf_irc(msgbuf, pattern, vl);
421   return exit_client(cptr, bcptr, sptr, msgbuf);
422 }
423
424 int exit_client_msg(struct Client *cptr, struct Client *bcptr,
425     struct Client *sptr, char *pattern, ...)
426 {
427   va_list vl;
428   char msgbuf[1024];
429
430   va_start(vl, pattern);
431   vsprintf_irc(msgbuf, pattern, vl);
432   va_end(vl);
433
434   return exit_client(cptr, bcptr, sptr, msgbuf);
435 }
436
437 /*
438  * Exit one client, local or remote. Assuming for local client that
439  * all dependants already have been removed, and socket is closed.
440  *
441  * Rewritten by Run - 24 sept 94
442  *
443  * bcptr : client being (s)quitted
444  * sptr : The source (prefix) of the QUIT or SQUIT
445  *
446  * --Run
447  */
448 static void exit_one_client(struct Client *bcptr, char *comment)
449 {
450   struct SLink *lp;
451
452   if (bcptr->serv && bcptr->serv->client_list)  /* Was SetServerYXX called ? */
453     ClearServerYXX(bcptr);      /* Removes server from server_list[] */
454   if (IsUser(bcptr)) {
455     /*
456      * Stop a running /LIST clean
457      */
458     if (MyUser(bcptr) && bcptr->listing) {
459       bcptr->listing->chptr->mode.mode &= ~MODE_LISTED;
460       MyFree(bcptr->listing);
461       bcptr->listing = NULL;
462     }
463     /*
464      * If a person is on a channel, send a QUIT notice
465      * to every client (person) on the same channel (so
466      * that the client can show the "**signoff" message).
467      * (Note: The notice is to the local clients *only*)
468      */
469     sendto_common_channels(bcptr, ":%s QUIT :%s", bcptr->name, comment);
470
471     remove_user_from_all_channels(bcptr);
472
473     /* Clean up invitefield */
474     while ((lp = bcptr->user->invited))
475       del_invite(bcptr, lp->value.chptr);
476
477     /* Clean up silencefield */
478     while ((lp = bcptr->user->silence))
479       del_silence(bcptr, lp->value.cp);
480
481     if (IsInvisible(bcptr))
482       --UserStats.inv_clients;
483     if (IsOper(bcptr))
484       --UserStats.opers;
485     if (MyConnect(bcptr))
486       Count_clientdisconnects(bcptr, UserStats);
487     else
488       Count_remoteclientquits(UserStats, bcptr);
489   }
490   else if (IsServer(bcptr))
491   {
492     /* Remove downlink list node of uplink */
493     remove_dlink(&bcptr->serv->up->serv->down, bcptr->serv->updown);
494     bcptr->serv->updown = 0;
495
496     if (MyConnect(bcptr))
497       Count_serverdisconnects(UserStats);
498     else
499       Count_remoteserverquits(UserStats);
500   }
501   else if (IsMe(bcptr))
502   {
503     sendto_ops("ERROR: tried to exit me! : %s", comment);
504     return;                     /* ...must *never* exit self! */
505   }
506   else if (IsUnknown(bcptr) || IsConnecting(bcptr) || IsHandshake(bcptr))
507     Count_unknowndisconnects(UserStats);
508
509   /*
510    * Update IPregistry
511    */
512   if (IsIPChecked(bcptr))
513     IPcheck_disconnect(bcptr);
514
515   /* 
516    * Remove from serv->client_list
517    * NOTE: user is *always* NULL if this is a server
518    */
519   if (bcptr->user) {
520     assert(!IsServer(bcptr));
521     /* bcptr->user->server->serv->client_list[IndexYXX(bcptr)] = NULL; */
522     RemoveYXXClient(bcptr->user->server, bcptr->yxx);
523   }
524
525   /* Remove bcptr from the client list */
526 #ifdef DEBUGMODE
527   if (hRemClient(bcptr) != 0)
528     Debug((DEBUG_ERROR, "%p !in tab %s[%s] %p %p %p %d %d %p",
529           bcptr, bcptr->name, bcptr->from ? bcptr->from->sockhost : "??host",
530           bcptr->from, bcptr->next, bcptr->prev, bcptr->fd,
531           bcptr->status, bcptr->user));
532 #else
533   hRemClient(bcptr);
534 #endif
535   remove_client_from_list(bcptr);
536 }
537
538
539 void initstats(void)
540 {
541   memset(&ircst, 0, sizeof(ircst));
542 }
543
544 void tstats(struct Client *cptr, char *name)
545 {
546   struct Client *acptr;
547   int i;
548   struct ServerStatistics *sp;
549   struct ServerStatistics tmp;
550
551   sp = &tmp;
552   memcpy(sp, ServerStats, sizeof(struct ServerStatistics));
553   for (i = 0; i < MAXCONNECTIONS; i++)
554   {
555     if (!(acptr = LocalClientArray[i]))
556       continue;
557     if (IsServer(acptr))
558     {
559       sp->is_sbs += acptr->sendB;
560       sp->is_sbr += acptr->receiveB;
561       sp->is_sks += acptr->sendK;
562       sp->is_skr += acptr->receiveK;
563       sp->is_sti += CurrentTime - acptr->firsttime;
564       sp->is_sv++;
565       if (sp->is_sbs > 1023)
566       {
567         sp->is_sks += (sp->is_sbs >> 10);
568         sp->is_sbs &= 0x3ff;
569       }
570       if (sp->is_sbr > 1023)
571       {
572         sp->is_skr += (sp->is_sbr >> 10);
573         sp->is_sbr &= 0x3ff;
574       }
575     }
576     else if (IsUser(acptr))
577     {
578       sp->is_cbs += acptr->sendB;
579       sp->is_cbr += acptr->receiveB;
580       sp->is_cks += acptr->sendK;
581       sp->is_ckr += acptr->receiveK;
582       sp->is_cti += CurrentTime - acptr->firsttime;
583       sp->is_cl++;
584       if (sp->is_cbs > 1023)
585       {
586         sp->is_cks += (sp->is_cbs >> 10);
587         sp->is_cbs &= 0x3ff;
588       }
589       if (sp->is_cbr > 1023)
590       {
591         sp->is_ckr += (sp->is_cbr >> 10);
592         sp->is_cbr &= 0x3ff;
593       }
594     }
595     else if (IsUnknown(acptr))
596       sp->is_ni++;
597   }
598
599   sendto_one(cptr, ":%s %d %s :accepts %u refused %u",
600       me.name, RPL_STATSDEBUG, name, sp->is_ac, sp->is_ref);
601   sendto_one(cptr, ":%s %d %s :unknown commands %u prefixes %u",
602       me.name, RPL_STATSDEBUG, name, sp->is_unco, sp->is_unpf);
603   sendto_one(cptr, ":%s %d %s :nick collisions %u unknown closes %u",
604       me.name, RPL_STATSDEBUG, name, sp->is_kill, sp->is_ni);
605   sendto_one(cptr, ":%s %d %s :wrong direction %u empty %u",
606       me.name, RPL_STATSDEBUG, name, sp->is_wrdi, sp->is_empt);
607   sendto_one(cptr, ":%s %d %s :numerics seen %u mode fakes %u",
608       me.name, RPL_STATSDEBUG, name, sp->is_num, sp->is_fake);
609   sendto_one(cptr, ":%s %d %s :auth successes %u fails %u",
610       me.name, RPL_STATSDEBUG, name, sp->is_asuc, sp->is_abad);
611   sendto_one(cptr, ":%s %d %s :local connections %u",
612       me.name, RPL_STATSDEBUG, name, sp->is_loc);
613   sendto_one(cptr, ":%s %d %s :Client Server", me.name, RPL_STATSDEBUG, name);
614   sendto_one(cptr, ":%s %d %s :connected %u %u",
615       me.name, RPL_STATSDEBUG, name, sp->is_cl, sp->is_sv);
616   sendto_one(cptr, ":%s %d %s :bytes sent %u.%uK %u.%uK",
617       me.name, RPL_STATSDEBUG, name,
618       sp->is_cks, sp->is_cbs, sp->is_sks, sp->is_sbs);
619   sendto_one(cptr, ":%s %d %s :bytes recv %u.%uK %u.%uK",
620       me.name, RPL_STATSDEBUG, name,
621       sp->is_ckr, sp->is_cbr, sp->is_skr, sp->is_sbr);
622   sendto_one(cptr, ":%s %d %s :time connected " TIME_T_FMT " " TIME_T_FMT,
623       me.name, RPL_STATSDEBUG, name, sp->is_cti, sp->is_sti);
624 }