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