e2f56ae57615d323c403461117bdbca7668ceb25
[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_auth.h"
35 #include "ircd_features.h"
36 #include "ircd_log.h"
37 #include "ircd_reply.h"
38 #include "ircd_snprintf.h"
39 #include "ircd_string.h"
40 #include "list.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     if (IsIAuthed(bcptr) || cli_iauth(bcptr))
300         iauth_exit_client(bcptr);
301   }
302
303   /* Remove bcptr from the client list */
304 #ifdef DEBUGMODE
305   if (hRemClient(bcptr) != 0)
306     Debug((DEBUG_ERROR, "%p !in tab %s[%s] %p %p %p %d %d %p",
307           bcptr, cli_name(bcptr), cli_from(bcptr) ? cli_sockhost(cli_from(bcptr)) : "??host",
308           cli_from(bcptr), cli_next(bcptr), cli_prev(bcptr), cli_fd(bcptr),
309           cli_status(bcptr), cli_user(bcptr)));
310 #else
311   hRemClient(bcptr);
312 #endif
313   remove_client_from_list(bcptr);
314 }
315
316 /*
317  * exit_downlinks - added by Run 25-9-94
318  *
319  * Removes all clients and downlinks (+clients) of any server
320  * QUITs are generated and sent to local users.
321  *
322  * cptr    : server that must have all dependents removed
323  * sptr    : source who thought that this was a good idea
324  * comment : comment sent as sign off message to local clients
325  */
326 static void exit_downlinks(struct Client *cptr, struct Client *sptr, char *comment)
327 {
328   struct Client *acptr;
329   struct DLink *next;
330   struct DLink *lp;
331   struct Client **acptrp;
332   int i;
333
334   /* Run over all its downlinks */
335   for (lp = cli_serv(cptr)->down; lp; lp = next)
336   {
337     next = lp->next;
338     acptr = lp->value.cptr;
339     /* Remove the downlinks and client of the downlink */
340     exit_downlinks(acptr, sptr, comment);
341     /* Remove the downlink itself */
342     exit_one_client(acptr, cli_name(&me));
343   }
344   /* Remove all clients of this server */
345   acptrp = cli_serv(cptr)->client_list;
346   for (i = 0; i <= cli_serv(cptr)->nn_mask; ++acptrp, ++i) {
347     if (*acptrp)
348       exit_one_client(*acptrp, comment);
349   }
350 }
351
352 /*
353  * exit_client, rewritten 25-9-94 by Run
354  *
355  * This function exits a client of *any* type (user, server, etc)
356  * from this server. Also, this generates all necessary prototol
357  * messages that this exit may cause.
358  *
359  * This function implicitly exits all other clients depending on
360  * this connection.
361  *
362  * For convenience, this function returns a suitable value for
363  * m_funtion return value:
364  *
365  *   CPTR_KILLED     if (cptr == bcptr)
366  *   0                if (cptr != bcptr)
367  *
368  * This function can be called in two ways:
369  * 1) From before or in parse(), exitting the 'cptr', in which case it was
370  *    invoked as exit_client(cptr, cptr, &me,...), causing it to always
371  *    return CPTR_KILLED.
372  * 2) Via parse from a m_function call, in which case it was invoked as
373  *    exit_client(cptr, acptr, sptr, ...). Here 'sptr' is known; the client
374  *    that generated the message in a way that we can assume he already
375  *    did remove acptr from memory himself (or in other cases we don't mind
376  *    because he will be delinked.) Or invoked as:
377  *    exit_client(cptr, acptr/sptr, &me, ...) when WE decide this one should
378  *    be removed.
379  * In general: No generated SQUIT or QUIT should be sent to source link
380  * sptr->from. And CPTR_KILLED should be returned if cptr got removed (too).
381  *
382  * --Run
383  */
384 int exit_client(struct Client *cptr,    /* Connection being handled by
385                                    read_message right now */
386     struct Client* victim,              /* Client being killed */
387     struct Client* killer,              /* The client that made the decision
388                                    to remove this one, never NULL */
389     const char* comment)              /* Reason for the exit */
390 {
391   struct Client* acptr = 0;
392   struct DLink *dlp;
393   time_t on_for;
394
395   char comment1[HOSTLEN + HOSTLEN + 2];
396   assert(killer);
397   if (MyConnect(victim))
398   {
399     SetFlag(victim, FLAG_CLOSING);
400
401     if (feature_bool(FEAT_CONNEXIT_NOTICES) && IsUser(victim))
402       sendto_opmask_butone(0, SNO_CONNEXIT,
403                            "Client exiting: %s (%s@%s) [%s] [%s] <%s%s>",
404                            cli_name(victim), cli_user(victim)->username,
405                            cli_user(victim)->host, comment,
406                            ircd_ntoa((const char*) &(cli_ip(victim))),
407                            NumNick(victim) /* two %s's */);
408     update_load();
409
410     on_for = CurrentTime - cli_firsttime(victim);
411
412     if (IsUser(victim))
413       log_write(LS_USER, L_TRACE, 0, "%Tu %i %s@%s %s %s %s%s %s :%s",
414                 cli_firsttime(victim), on_for,
415                 cli_user(victim)->username, cli_sockhost(victim),
416                 ircd_ntoa((const char*) &(cli_ip(victim))),
417                 IsAccount(victim) ? cli_username(victim) : "0",
418                 NumNick(victim), /* two %s's */
419                 cli_name(victim), cli_info(victim));
420
421     if (victim != cli_from(killer)  /* The source knows already */
422         && IsClient(victim))    /* Not a Ping struct or Log file */
423     {
424       if (IsServer(victim) || IsHandshake(victim))
425         sendcmdto_one(killer, CMD_SQUIT, victim, "%s 0 :%s", cli_name(&me), comment);
426       else if (!IsConnecting(victim)) {
427         if (!IsDead(victim)) {
428           if (IsServer(victim))
429             sendcmdto_one(killer, CMD_ERROR, victim,
430                           ":Closing Link: %s by %s (%s)", cli_name(victim),
431                           cli_name(killer), comment);
432           else
433             sendrawto_one(victim, MSG_ERROR " :Closing Link: %s by %s (%s)",
434                           cli_name(victim), IsServer(killer) ? cli_name(&me) :
435                           cli_name(killer), comment);
436         }
437       }
438       if ((IsServer(victim) || IsHandshake(victim) || IsConnecting(victim)) &&
439           (killer == &me || (IsServer(killer) &&
440           (strncmp(comment, "Leaf-only link", 14) ||
441           strncmp(comment, "Non-Hub link", 12)))))
442       {
443         /*
444          * Note: check user == user needed to make sure we have the same
445          * client
446          */
447         if (cli_serv(victim)->user && *(cli_serv(victim))->by &&
448             (acptr = findNUser(cli_serv(victim)->by))) {
449           if (cli_user(acptr) == cli_serv(victim)->user) {
450             sendcmdto_one(&me, CMD_NOTICE, acptr,
451                           "%C :Link with %s cancelled: %s", acptr,
452                           cli_name(victim), comment);
453           }
454           else {
455             /*
456              * not right client, set by to empty string
457              */
458             acptr = 0;
459             *(cli_serv(victim))->by = '\0';
460           }
461         }
462         if (killer == &me)
463           sendto_opmask_butone(acptr, SNO_OLDSNO, "Link with %s cancelled: %s",
464                                cli_name(victim), comment);
465       }
466     }
467     /*
468      *  Close the Client connection first.
469      */
470     close_connection(victim);
471   }
472
473   if (IsServer(victim))
474   {
475     if (feature_bool(FEAT_HIS_NETSPLIT))
476       strcpy(comment1, "*.net *.split");
477     else
478     {
479       strcpy(comment1, cli_name(cli_serv(victim)->up));
480       strcat(comment1, " ");
481       strcat(comment1, cli_name(victim));
482     }
483
484     if (IsUser(killer))
485       sendto_opmask_butone(killer, SNO_OLDSNO, "%s SQUIT by %s [%s]:",
486                            (cli_user(killer)->server == victim ||
487                             cli_user(killer)->server == cli_serv(victim)->up) ?
488                            "Local" : "Remote",
489                            get_client_name(killer, HIDE_IP),
490                            cli_name(cli_user(killer)->server));
491     else if (killer != &me && cli_serv(victim)->up != killer)
492       sendto_opmask_butone(0, SNO_OLDSNO, "Received SQUIT %s from %s :",
493                            cli_name(victim), IsServer(killer) ? cli_name(killer) :
494                            get_client_name(killer, HIDE_IP));
495     sendto_opmask_butone(0, SNO_NETWORK, "Net break: %C %C (%s)",
496                          cli_serv(victim)->up, victim, comment);
497   }
498
499   /*
500    * First generate the needed protocol for the other server links
501    * except the source:
502    */
503   for (dlp = cli_serv(&me)->down; dlp; dlp = dlp->next) {
504     if (dlp->value.cptr != cli_from(killer) && dlp->value.cptr != victim)
505     {
506       if (IsServer(victim))
507         sendcmdto_one(killer, CMD_SQUIT, dlp->value.cptr, "%s %Tu :%s",
508                       cli_name(victim), cli_serv(victim)->timestamp, comment);
509       else if (IsUser(victim) && !HasFlag(victim, FLAG_KILLED))
510         sendcmdto_one(victim, CMD_QUIT, dlp->value.cptr, ":%s", comment);
511     }
512   }
513   /* Then remove the client structures */
514   if (IsServer(victim))
515     exit_downlinks(victim, killer, comment1);
516   exit_one_client(victim, comment);
517
518   /*
519    *  cptr can only have been killed if it was cptr itself that got killed here,
520    *  because cptr can never have been a dependant of victim    --Run
521    */
522   return (cptr == victim) ? CPTR_KILLED : 0;
523 }
524
525 /*
526  * Exit client with formatted message, added 25-9-94 by Run
527  */
528 int vexit_client_msg(struct Client *cptr, struct Client *bcptr, struct Client *sptr,
529     const char *pattern, va_list vl)
530 {
531   char msgbuf[1024];
532   ircd_vsnprintf(0, msgbuf, sizeof(msgbuf), pattern, vl);
533   return exit_client(cptr, bcptr, sptr, msgbuf);
534 }
535
536 int exit_client_msg(struct Client *cptr, struct Client *bcptr,
537     struct Client *sptr, const char *pattern, ...)
538 {
539   va_list vl;
540   char msgbuf[1024];
541
542   va_start(vl, pattern);
543   ircd_vsnprintf(0, msgbuf, sizeof(msgbuf), pattern, vl);
544   va_end(vl);
545
546   return exit_client(cptr, bcptr, sptr, msgbuf);
547 }
548
549 void initstats(void)
550 {
551   memset(&ircst, 0, sizeof(ircst));
552 }
553
554 void tstats(struct Client *cptr, struct StatDesc *sd, int stat, char *param)
555 {
556   struct Client *acptr;
557   int i;
558   struct ServerStatistics *sp;
559   struct ServerStatistics tmp;
560
561   sp = &tmp;
562   memcpy(sp, ServerStats, sizeof(struct ServerStatistics));
563   for (i = 0; i < MAXCONNECTIONS; i++)
564   {
565     if (!(acptr = LocalClientArray[i]))
566       continue;
567     if (IsServer(acptr))
568     {
569       sp->is_sbs += cli_sendB(acptr);
570       sp->is_sbr += cli_receiveB(acptr);
571       sp->is_sks += cli_sendK(acptr);
572       sp->is_skr += cli_receiveK(acptr);
573       sp->is_sti += CurrentTime - cli_firsttime(acptr);
574       sp->is_sv++;
575       if (sp->is_sbs > 1023)
576       {
577         sp->is_sks += (sp->is_sbs >> 10);
578         sp->is_sbs &= 0x3ff;
579       }
580       if (sp->is_sbr > 1023)
581       {
582         sp->is_skr += (sp->is_sbr >> 10);
583         sp->is_sbr &= 0x3ff;
584       }
585     }
586     else if (IsUser(acptr))
587     {
588       sp->is_cbs += cli_sendB(acptr);
589       sp->is_cbr += cli_receiveB(acptr);
590       sp->is_cks += cli_sendK(acptr);
591       sp->is_ckr += cli_receiveK(acptr);
592       sp->is_cti += CurrentTime - cli_firsttime(acptr);
593       sp->is_cl++;
594       if (sp->is_cbs > 1023)
595       {
596         sp->is_cks += (sp->is_cbs >> 10);
597         sp->is_cbs &= 0x3ff;
598       }
599       if (sp->is_cbr > 1023)
600       {
601         sp->is_ckr += (sp->is_cbr >> 10);
602         sp->is_cbr &= 0x3ff;
603       }
604     }
605     else if (IsUnknown(acptr))
606       sp->is_ni++;
607   }
608
609   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":accepts %u refused %u",
610              sp->is_ac, sp->is_ref);
611   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
612              ":unknown commands %u prefixes %u", sp->is_unco, sp->is_unpf);
613   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
614              ":nick collisions %u unknown closes %u", sp->is_kill, sp->is_ni);
615   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
616              ":wrong direction %u empty %u", sp->is_wrdi, sp->is_empt);
617   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
618              ":numerics seen %u mode fakes %u", sp->is_num, sp->is_fake);
619   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG,
620              ":auth successes %u fails %u", sp->is_asuc, sp->is_abad);
621   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":local connections %u",
622              sp->is_loc);
623   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":Client server");
624   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":connected %u %u",
625              sp->is_cl, sp->is_sv);
626   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":bytes sent %u.%uK %u.%uK",
627              sp->is_cks, sp->is_cbs, sp->is_sks, sp->is_sbs);
628   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":bytes recv %u.%uK %u.%uK",
629              sp->is_ckr, sp->is_cbr, sp->is_skr, sp->is_sbr);
630   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":time connected %Tu %Tu",
631              sp->is_cti, sp->is_sti);
632 }