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