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