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