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