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 "uping.h"
52 #include "userload.h"
53
54 #include <assert.h>
55 #include <fcntl.h>
56 #include <netdb.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <sys/stat.h>
60 #include <unistd.h>
61
62 static void exit_one_client(struct Client *, char *);
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_downlinks - added by Run 25-9-94
204  *
205  * Removes all clients and downlinks (+clients) of any server
206  * QUITs are generated and sent to local users.
207  *
208  * cptr    : server that must have all dependents removed
209  * sptr    : source who thought that this was a good idea
210  * comment : comment sent as sign off message to local clients
211  */
212 static void exit_downlinks(struct Client *cptr, struct Client *sptr, char *comment)
213 {
214   struct Client *acptr;
215   struct DLink *next;
216   struct DLink *lp;
217   struct Client **acptrp;
218   int i;
219
220   /* Run over all its downlinks */
221   for (lp = cptr->serv->down; lp; lp = next)
222   {
223     next = lp->next;
224     acptr = lp->value.cptr;
225     /* Remove the downlinks and client of the downlink */
226     exit_downlinks(acptr, sptr, comment);
227     /* Remove the downlink itself */
228     exit_one_client(acptr, me.name);
229   }
230   /* Remove all clients of this server */
231   acptrp = cptr->serv->client_list;
232   for (i = 0; i <= cptr->serv->nn_mask; ++acptrp, ++i) {
233     if (*acptrp)
234       exit_one_client(*acptrp, comment);
235   }
236 }
237
238 /*
239  * exit_client, rewritten 25-9-94 by Run
240  *
241  * This function exits a client of *any* type (user, server, etc)
242  * from this server. Also, this generates all necessary prototol
243  * messages that this exit may cause.
244  *
245  * This function implicitly exits all other clients depending on
246  * this connection.
247  *
248  * For convenience, this function returns a suitable value for
249  * m_funtion return value:
250  *
251  *   CPTR_KILLED     if (cptr == bcptr)
252  *   0                if (cptr != bcptr)
253  *
254  * This function can be called in two ways:
255  * 1) From before or in parse(), exitting the 'cptr', in which case it was
256  *    invoked as exit_client(cptr, cptr, &me,...), causing it to always
257  *    return CPTR_KILLED.
258  * 2) Via parse from a m_function call, in which case it was invoked as
259  *    exit_client(cptr, acptr, sptr, ...). Here 'sptr' is known; the client
260  *    that generated the message in a way that we can assume he already
261  *    did remove acptr from memory himself (or in other cases we don't mind
262  *    because he will be delinked.) Or invoked as:
263  *    exit_client(cptr, acptr/sptr, &me, ...) when WE decide this one should
264  *    be removed.
265  * In general: No generated SQUIT or QUIT should be sent to source link
266  * sptr->from. And CPTR_KILLED should be returned if cptr got removed (too).
267  *
268  * --Run
269  */
270 int exit_client(struct Client *cptr,    /* Connection being handled by
271                                    read_message right now */
272     struct Client* victim,              /* Client being killed */
273     struct Client* killer,              /* The client that made the decision
274                                    to remove this one, never NULL */
275     char *comment)              /* Reason for the exit */
276 {
277   struct Client* acptr = 0;
278   struct DLink *dlp;
279 #ifdef  FNAME_USERLOG
280   time_t on_for;
281 #endif
282   char comment1[HOSTLEN + HOSTLEN + 2];
283
284   if (MyConnect(victim)) {
285     victim->flags |= FLAGS_CLOSING;
286 #ifdef ALLOW_SNO_CONNEXIT
287 #ifdef SNO_CONNEXIT_IP
288     if (IsUser(victim)) {
289       sprintf_irc(sendbuf,
290           ":%s NOTICE * :*** Notice -- Client exiting: %s (%s@%s) [%s] [%s]",
291           me.name, victim->name, victim->user->username, victim->user->host,
292           comment, ircd_ntoa((const char*) &victim->ip));
293       sendbufto_op_mask(SNO_CONNEXIT);
294     }
295 #else /* SNO_CONNEXIT_IP */
296     if (IsUser(victim)) {
297       sprintf_irc(sendbuf,
298           ":%s NOTICE * :*** Notice -- Client exiting: %s (%s@%s) [%s]",
299           me.name, victim->name, victim->user->username, victim->user->host,
300           comment);
301       sendbufto_op_mask(SNO_CONNEXIT);
302     }
303 #endif /* SNO_CONNEXIT_IP */
304 #endif /* ALLOW_SNO_CONNEXIT */
305     update_load();
306 #ifdef FNAME_USERLOG
307     on_for = CurrentTime - victim->firsttime;
308 #if defined(USE_SYSLOG) && defined(SYSLOG_USERS)
309     if (IsUser(victim))
310       ircd_log(L_TRACE, "%s (%3d:%02d:%02d): %s@%s (%s)\n",
311                myctime(victim->firsttime), on_for / 3600, (on_for % 3600) / 60,
312                on_for % 60, victim->user->username, victim->sockhost, victim->name);
313 #else
314     if (IsUser(victim))
315       write_log(FNAME_USERLOG,
316                "%s (%3d:%02d:%02d): %s@%s [%s]\n",
317                myctime(victim->firsttime),
318                on_for / 3600, (on_for % 3600) / 60,
319                on_for % 60,
320                victim->user->username, victim->user->host, victim->username);
321 #endif
322 #endif
323     if (victim != killer->from  /* The source knows already */
324         && IsClient(victim))    /* Not a Ping struct or Log file */
325     {
326       if (IsServer(victim) || IsHandshake(victim))
327         sendto_one(victim, ":%s " TOK_SQUIT " %s 0 :%s", killer->name, me.name, comment);
328       else if (!IsConnecting(victim)) {
329         if (!IsDead(victim))
330           sendto_one(victim, "ERROR :Closing Link: %s by %s (%s)",
331                      victim->name, killer->name, comment);
332       }
333       if ((IsServer(victim) || IsHandshake(victim) || IsConnecting(victim)) &&
334           (killer == &me || (IsServer(killer) &&
335           (strncmp(comment, "Leaf-only link", 14) ||
336           strncmp(comment, "Non-Hub link", 12)))))
337       {
338         /*
339          * Note: check user == user needed to make sure we have the same
340          * client
341          */
342         if (victim->serv->user && *victim->serv->by &&
343             (acptr = findNUser(victim->serv->by))) {
344           if (acptr->user == victim->serv->user) {
345             if (MyUser(acptr) || Protocol(acptr->from) < 10)
346               sendto_one(acptr,
347                          ":%s NOTICE %s :Link with %s cancelled: %s",
348                          me.name, acptr->name, victim->name, comment);
349             else
350               sendto_one(acptr,
351                          "%s NOTICE %s%s :Link with %s cancelled: %s",
352                          NumServ(&me), NumNick(acptr), victim->name, comment);
353           }
354           else {
355             /*
356              * not right client, set by to empty string
357              */
358             acptr = 0;
359             *victim->serv->by = '\0';
360           }
361         }
362         if (killer == &me)
363           sendto_lops_butone(acptr, "Link with %s cancelled: %s",
364                              victim->name, comment);
365       }
366     }
367     /*
368      *  Close the Client connection first.
369      */
370     close_connection(victim);
371   }
372
373   if (IsServer(victim))
374   {
375     strcpy(comment1, victim->serv->up->name);
376     strcat(comment1, " ");
377     strcat(comment1, victim->name);
378     if (IsUser(killer))
379       sendto_lops_butone(killer, "%s SQUIT by %s [%s]:",
380                          (killer->user->server == victim ||
381                          killer->user->server == victim->serv->up) ? "Local" : "Remote",
382                          get_client_name(killer, HIDE_IP), killer->user->server->name);
383     else if (killer != &me && victim->serv->up != killer)
384       sendto_ops("Received SQUIT %s from %s :", victim->name,
385                  IsServer(killer) ? killer->name : get_client_name(killer, HIDE_IP));
386     sendto_op_mask(SNO_NETWORK, "Net break: %s (%s)", comment1, comment);
387   }
388
389   /*
390    * First generate the needed protocol for the other server links
391    * except the source:
392    */
393   for (dlp = me.serv->down; dlp; dlp = dlp->next) {
394     if (dlp->value.cptr != killer->from && dlp->value.cptr != victim) {
395       if (IsServer(victim))
396         sendto_one(dlp->value.cptr, ":%s " TOK_SQUIT " %s " TIME_T_FMT " :%s",
397                    killer->name, victim->name, victim->serv->timestamp, comment);
398       else if (IsUser(victim) && 0 == (victim->flags & FLAGS_KILLED))
399         sendto_one(dlp->value.cptr, "%s%s " TOK_QUIT " :%s", NumNick(victim), comment);
400     }
401   }
402   /* Then remove the client structures */
403   if (IsServer(victim))
404     exit_downlinks(victim, killer, comment1);
405   exit_one_client(victim, comment);
406
407   /*
408    *  cptr can only have been killed if it was cptr itself that got killed here,
409    *  because cptr can never have been a dependant of victim    --Run
410    */
411   return (cptr == victim) ? CPTR_KILLED : 0;
412 }
413
414 /*
415  * Exit client with formatted message, added 25-9-94 by Run
416  */
417 int vexit_client_msg(struct Client *cptr, struct Client *bcptr, struct Client *sptr,
418     char *pattern, va_list vl)
419 {
420   char msgbuf[1024];
421   vsprintf_irc(msgbuf, pattern, vl);
422   return exit_client(cptr, bcptr, sptr, msgbuf);
423 }
424
425 int exit_client_msg(struct Client *cptr, struct Client *bcptr,
426     struct Client *sptr, char *pattern, ...)
427 {
428   va_list vl;
429   char msgbuf[1024];
430
431   va_start(vl, pattern);
432   vsprintf_irc(msgbuf, pattern, vl);
433   va_end(vl);
434
435   return exit_client(cptr, bcptr, sptr, msgbuf);
436 }
437
438 /*
439  * Exit one client, local or remote. Assuming for local client that
440  * all dependants already have been removed, and socket is closed.
441  *
442  * Rewritten by Run - 24 sept 94
443  *
444  * bcptr : client being (s)quitted
445  * sptr : The source (prefix) of the QUIT or SQUIT
446  *
447  * --Run
448  */
449 static void exit_one_client(struct Client *bcptr, char *comment)
450 {
451   struct SLink *lp;
452
453   if (bcptr->serv && bcptr->serv->client_list)  /* Was SetServerYXX called ? */
454     ClearServerYXX(bcptr);      /* Removes server from server_list[] */
455   if (IsUser(bcptr)) {
456     /*
457      * clear out uping requests
458      */
459     if (IsUPing(bcptr))
460       uping_cancel(bcptr, 0);
461     /*
462      * Stop a running /LIST clean
463      */
464     if (MyUser(bcptr) && bcptr->listing) {
465       bcptr->listing->chptr->mode.mode &= ~MODE_LISTED;
466       MyFree(bcptr->listing);
467       bcptr->listing = NULL;
468     }
469     /*
470      * If a person is on a channel, send a QUIT notice
471      * to every client (person) on the same channel (so
472      * that the client can show the "**signoff" message).
473      * (Note: The notice is to the local clients *only*)
474      */
475     sendto_common_channels(bcptr, ":%s QUIT :%s", bcptr->name, comment);
476
477     remove_user_from_all_channels(bcptr);
478
479     /* Clean up invitefield */
480     while ((lp = bcptr->user->invited))
481       del_invite(bcptr, lp->value.chptr);
482
483     /* Clean up silencefield */
484     while ((lp = bcptr->user->silence))
485       del_silence(bcptr, lp->value.cp);
486
487     if (IsInvisible(bcptr))
488       --UserStats.inv_clients;
489     if (IsOper(bcptr))
490       --UserStats.opers;
491     if (MyConnect(bcptr))
492       Count_clientdisconnects(bcptr, UserStats);
493     else
494       Count_remoteclientquits(UserStats, bcptr);
495   }
496   else if (IsServer(bcptr))
497   {
498     /* Remove downlink list node of uplink */
499     remove_dlink(&bcptr->serv->up->serv->down, bcptr->serv->updown);
500     bcptr->serv->updown = 0;
501
502     if (MyConnect(bcptr))
503       Count_serverdisconnects(UserStats);
504     else
505       Count_remoteserverquits(UserStats);
506   }
507   else if (IsMe(bcptr))
508   {
509     sendto_ops("ERROR: tried to exit me! : %s", comment);
510     return;                     /* ...must *never* exit self! */
511   }
512   else if (IsUnknown(bcptr) || IsConnecting(bcptr) || IsHandshake(bcptr))
513     Count_unknowndisconnects(UserStats);
514
515   /*
516    * Update IPregistry
517    */
518   if (IsIPChecked(bcptr))
519     IPcheck_disconnect(bcptr);
520
521   /* 
522    * Remove from serv->client_list
523    * NOTE: user is *always* NULL if this is a server
524    */
525   if (bcptr->user) {
526     assert(!IsServer(bcptr));
527     /* bcptr->user->server->serv->client_list[IndexYXX(bcptr)] = NULL; */
528     RemoveYXXClient(bcptr->user->server, bcptr->yxx);
529   }
530
531   /* Remove bcptr from the client list */
532 #ifdef DEBUGMODE
533   if (hRemClient(bcptr) != 0)
534     Debug((DEBUG_ERROR, "%p !in tab %s[%s] %p %p %p %d %d %p",
535           bcptr, bcptr->name, bcptr->from ? bcptr->from->sockhost : "??host",
536           bcptr->from, bcptr->next, bcptr->prev, bcptr->fd,
537           bcptr->status, bcptr->user));
538 #else
539   hRemClient(bcptr);
540 #endif
541   remove_client_from_list(bcptr);
542 }
543
544
545 void initstats(void)
546 {
547   memset(&ircst, 0, sizeof(ircst));
548 }
549
550 void tstats(struct Client *cptr, char *name)
551 {
552   struct Client *acptr;
553   int i;
554   struct ServerStatistics *sp;
555   struct ServerStatistics tmp;
556
557   sp = &tmp;
558   memcpy(sp, ServerStats, sizeof(struct ServerStatistics));
559   for (i = 0; i < MAXCONNECTIONS; i++)
560   {
561     if (!(acptr = LocalClientArray[i]))
562       continue;
563     if (IsServer(acptr))
564     {
565       sp->is_sbs += acptr->sendB;
566       sp->is_sbr += acptr->receiveB;
567       sp->is_sks += acptr->sendK;
568       sp->is_skr += acptr->receiveK;
569       sp->is_sti += CurrentTime - acptr->firsttime;
570       sp->is_sv++;
571       if (sp->is_sbs > 1023)
572       {
573         sp->is_sks += (sp->is_sbs >> 10);
574         sp->is_sbs &= 0x3ff;
575       }
576       if (sp->is_sbr > 1023)
577       {
578         sp->is_skr += (sp->is_sbr >> 10);
579         sp->is_sbr &= 0x3ff;
580       }
581     }
582     else if (IsUser(acptr))
583     {
584       sp->is_cbs += acptr->sendB;
585       sp->is_cbr += acptr->receiveB;
586       sp->is_cks += acptr->sendK;
587       sp->is_ckr += acptr->receiveK;
588       sp->is_cti += CurrentTime - acptr->firsttime;
589       sp->is_cl++;
590       if (sp->is_cbs > 1023)
591       {
592         sp->is_cks += (sp->is_cbs >> 10);
593         sp->is_cbs &= 0x3ff;
594       }
595       if (sp->is_cbr > 1023)
596       {
597         sp->is_ckr += (sp->is_cbr >> 10);
598         sp->is_cbr &= 0x3ff;
599       }
600     }
601     else if (IsUnknown(acptr))
602       sp->is_ni++;
603   }
604
605   sendto_one(cptr, ":%s %d %s :accepts %u refused %u",
606       me.name, RPL_STATSDEBUG, name, sp->is_ac, sp->is_ref);
607   sendto_one(cptr, ":%s %d %s :unknown commands %u prefixes %u",
608       me.name, RPL_STATSDEBUG, name, sp->is_unco, sp->is_unpf);
609   sendto_one(cptr, ":%s %d %s :nick collisions %u unknown closes %u",
610       me.name, RPL_STATSDEBUG, name, sp->is_kill, sp->is_ni);
611   sendto_one(cptr, ":%s %d %s :wrong direction %u empty %u",
612       me.name, RPL_STATSDEBUG, name, sp->is_wrdi, sp->is_empt);
613   sendto_one(cptr, ":%s %d %s :numerics seen %u mode fakes %u",
614       me.name, RPL_STATSDEBUG, name, sp->is_num, sp->is_fake);
615   sendto_one(cptr, ":%s %d %s :auth successes %u fails %u",
616       me.name, RPL_STATSDEBUG, name, sp->is_asuc, sp->is_abad);
617   sendto_one(cptr, ":%s %d %s :local connections %u",
618       me.name, RPL_STATSDEBUG, name, sp->is_loc);
619   sendto_one(cptr, ":%s %d %s :Client Server", me.name, RPL_STATSDEBUG, name);
620   sendto_one(cptr, ":%s %d %s :connected %u %u",
621       me.name, RPL_STATSDEBUG, name, sp->is_cl, sp->is_sv);
622   sendto_one(cptr, ":%s %d %s :bytes sent %u.%uK %u.%uK",
623       me.name, RPL_STATSDEBUG, name,
624       sp->is_cks, sp->is_cbs, sp->is_sks, sp->is_sbs);
625   sendto_one(cptr, ":%s %d %s :bytes recv %u.%uK %u.%uK",
626       me.name, RPL_STATSDEBUG, name,
627       sp->is_ckr, sp->is_cbr, sp->is_skr, sp->is_sbr);
628   sendto_one(cptr, ":%s %d %s :time connected " TIME_T_FMT " " TIME_T_FMT,
629       me.name, RPL_STATSDEBUG, name, sp->is_cti, sp->is_sti);
630 }