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