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