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