1 /*
2 * ircd-hybrid: an advanced, lightweight Internet Relay Chat Daemon (ircd)
3 *
4 * Copyright (c) 1997-2021 ircd-hybrid development team
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 */
21
22 /*! \file server.c
23 * \brief Server related functions.
24 * \version $Id: server.c 9922 2021-03-21 06:39:52Z michael $
25 */
26
27 #include "stdinc.h"
28 #include "list.h"
29 #include "client.h"
30 #include "event.h"
31 #include "hash.h"
32 #include "irc_string.h"
33 #include "ircd.h"
34 #include "ircd_defs.h"
35 #include "s_bsd.h"
36 #include "packet.h"
37 #include "conf.h"
38 #include "server.h"
39 #include "server_capab.h"
40 #include "log.h"
41 #include "send.h"
42 #include "memory.h"
43 #include "parse.h"
44
45
46 dlink_list flatten_links;
47 static void server_connect_callback(fde_t *, int, void *);
48
49
50 /*
51 * write_links_file
52 *
53 * inputs - void pointer which is not used
54 * output - NONE
55 * side effects - called from an event, write out list of linked servers
56 * but in no particular order.
57 */
58 void
write_links_file(void * unused)59 write_links_file(void *unused)
60 {
61 char buf[IRCD_BUFSIZE];
62 dlink_node *node, *node_next;
63
64 if (EmptyString(ConfigServerHide.flatten_links_file))
65 return;
66
67 FILE *file = fopen(ConfigServerHide.flatten_links_file, "w");
68 if (file == NULL)
69 {
70 ilog(LOG_TYPE_IRCD, "Couldn't open \"%s\": %s", ConfigServerHide.flatten_links_file,
71 strerror(errno));
72 return;
73 }
74
75 DLINK_FOREACH_SAFE(node, node_next, flatten_links.head)
76 {
77 dlinkDelete(node, &flatten_links);
78 xfree(node->data);
79 free_dlink_node(node);
80 }
81
82 DLINK_FOREACH(node, global_server_list.head)
83 {
84 const struct Client *client = node->data;
85
86 /*
87 * Skip hidden servers, aswell as ourselves, since we already send
88 * ourselves in /links
89 */
90 if (IsHidden(client) || IsMe(client))
91 continue;
92
93 if (HasFlag(client, FLAGS_SERVICE) && ConfigServerHide.hide_services)
94 continue;
95
96 /*
97 * Attempt to format the file in such a way it follows the usual links output
98 * ie "servername uplink :hops info"
99 * Mostly for aesthetic reasons - makes it look pretty in mIRC ;)
100 * - madmax
101 */
102 snprintf(buf, sizeof(buf), "%s %s :1 %s", client->name, me.name, client->info);
103 dlinkAddTail(xstrdup(buf), make_dlink_node(), &flatten_links);
104
105 strlcat(buf, "\n", sizeof(buf));
106 fputs(buf, file);
107 }
108
109 fclose(file);
110 }
111
112 void
read_links_file(void)113 read_links_file(void)
114 {
115 char buf[IRCD_BUFSIZE];
116
117 if (EmptyString(ConfigServerHide.flatten_links_file))
118 return;
119
120 FILE *file = fopen(ConfigServerHide.flatten_links_file, "r");
121 if (file == NULL)
122 {
123 ilog(LOG_TYPE_IRCD, "Couldn't open \"%s\": %s", ConfigServerHide.flatten_links_file,
124 strerror(errno));
125 return;
126 }
127
128 while (fgets(buf, sizeof(buf), file))
129 {
130 char *p = strchr(buf, '\n');
131 if (p)
132 *p = '\0';
133
134 dlinkAddTail(xstrdup(buf), make_dlink_node(), &flatten_links);
135 }
136
137 fclose(file);
138 }
139
140 /* server_hunt()
141 * Do the basic thing in delivering the message (command)
142 * across the relays to the specific server (server) for
143 * actions.
144 *
145 * Note: The command is a format string and *MUST* be
146 * of prefixed style (e.g. ":%s COMMAND %s ...").
147 * Command can have only max 8 parameters.
148 *
149 * server parv[server] is the parameter identifying the
150 * target server.
151 *
152 * *WARNING*
153 * parv[server] is replaced with the pointer to the
154 * real servername from the matched client (I'm lazy
155 * now --msa).
156 *
157 * returns: (see #defines)
158 */
159 const struct server_hunt *
server_hunt(struct Client * source_p,const char * command,const int server,char * parv[])160 server_hunt(struct Client *source_p, const char *command, const int server, char *parv[])
161 {
162 static struct server_hunt hunt;
163 struct server_hunt *const h = &hunt;
164 dlink_node *node;
165 const char *const mask = parv[server];
166
167 /* Assume it's me, if no server */
168 if (EmptyString(mask))
169 {
170 h->target_p = &me;
171 h->ret = HUNTED_ISME;
172 return h;
173 }
174
175 h->target_p = find_person(source_p, mask);
176 if (h->target_p == NULL)
177 h->target_p = hash_find_server(mask);
178
179 /*
180 * These are to pickup matches that would cause the following
181 * message to go in the wrong direction while doing quick fast
182 * non-matching lookups.
183 */
184 if (h->target_p)
185 if (h->target_p->from == source_p->from && !MyConnect(h->target_p))
186 h->target_p = NULL;
187
188 if (h->target_p == NULL && has_wildcards(mask))
189 {
190 DLINK_FOREACH(node, global_server_list.head)
191 {
192 struct Client *tmp = node->data;
193
194 assert(IsMe(tmp) || IsServer(tmp));
195 if (match(mask, tmp->name) == 0)
196 {
197 if (tmp->from == source_p->from && !MyConnect(tmp))
198 continue;
199
200 h->target_p = tmp;
201 break;
202 }
203 }
204
205 if (h->target_p == NULL)
206 {
207 DLINK_FOREACH(node, global_client_list.head)
208 {
209 struct Client *tmp = node->data;
210
211 assert(IsClient(tmp));
212 if (match(mask, tmp->name) == 0)
213 {
214 if (tmp->from == source_p->from && !MyConnect(tmp))
215 continue;
216
217 h->target_p = tmp;
218 break;
219 }
220 }
221 }
222 }
223
224 if (h->target_p)
225 {
226 assert(IsMe(h->target_p) || IsServer(h->target_p) || IsClient(h->target_p));
227 if (IsMe(h->target_p) || MyClient(h->target_p))
228 {
229 h->ret = HUNTED_ISME;
230 return h;
231 }
232
233 parv[server] = h->target_p->id;
234 sendto_one(h->target_p, command, source_p->id,
235 parv[1], parv[2], parv[3], parv[4],
236 parv[5], parv[6], parv[7], parv[8]);
237 h->ret = HUNTED_PASS;
238 return h;
239 }
240
241 sendto_one_numeric(source_p, &me, ERR_NOSUCHSERVER, mask);
242 h->ret = HUNTED_NOSUCH;
243 return h;
244 }
245
246 /* try_connections()
247 *
248 * inputs - void pointer which is not used
249 * output - NONE
250 * side effects -
251 * scan through configuration and try new connections.
252 * Returns the calendar time when the next call to this
253 * function should be made latest. (No harm done if this
254 * is called earlier or later...)
255 */
256 void
try_connections(void * unused)257 try_connections(void *unused)
258 {
259 dlink_node *node;
260
261 if (GlobalSetOptions.autoconn == false)
262 return;
263
264 DLINK_FOREACH(node, connect_items.head)
265 {
266 struct MaskItem *conf = node->data;
267
268 assert(conf->type == CONF_SERVER);
269 assert(conf->class);
270
271 /* Also when already connecting! (update holdtimes) --SRB */
272 if (conf->port == 0 || !IsConfAllowAutoConn(conf))
273 continue;
274
275 /*
276 * Skip this entry if the use of it is still on hold until
277 * future. Otherwise handle this entry (and set it on hold
278 * until next time). Will reset only hold times, if already
279 * made one successfull connection... [this algorithm is
280 * a bit fuzzy... -- msa >;) ]
281 */
282 if (conf->until > event_base->time.sec_monotonic)
283 continue;
284
285 conf->until = event_base->time.sec_monotonic + conf->class->con_freq;
286
287 /*
288 * Found a CONNECT config with port specified, scan clients
289 * and see if this server is already connected?
290 */
291 if (hash_find_server(conf->name))
292 continue;
293
294 if (conf->class->ref_count < conf->class->max_total)
295 {
296 /* Move this entry to the end of the list, if not already last */
297 if (node->next)
298 {
299 dlinkDelete(node, &connect_items);
300 dlinkAddTail(conf, &conf->node, &connect_items);
301 }
302
303 if (find_servconn_in_progress(conf->name))
304 return;
305
306 /*
307 * We used to only print this if server_connect() actually
308 * succeeded, but since comm_tcp_connect() can call the callback
309 * immediately if there is an error, we were getting error messages
310 * in the wrong order. SO, we just print out the activated line,
311 * and let server_connect() / server_connect_callback() print an
312 * error afterwards if it fails.
313 * -- adrian
314 */
315 if (ConfigServerHide.hide_server_ips)
316 sendto_realops_flags(UMODE_SERVNOTICE, L_ALL, SEND_NOTICE,
317 "Connection to %s activated.",
318 conf->name);
319 else
320 sendto_realops_flags(UMODE_SERVNOTICE, L_ALL, SEND_NOTICE,
321 "Connection to %s[%s] activated.",
322 conf->name, conf->host);
323
324 server_connect(conf, NULL);
325 /* We connect only one at time... */
326 return;
327 }
328 }
329 }
330
331 bool
server_valid_name(const char * name)332 server_valid_name(const char *name)
333 {
334 unsigned int dots = 0;
335 const char *p = name;
336
337 for (; *p; ++p)
338 {
339 if (!IsServChar(*p))
340 return false;
341
342 if (*p == '.')
343 ++dots;
344 }
345
346 return dots && (p - name) <= HOSTLEN;
347 }
348
349 /* server_make()
350 *
351 * inputs - pointer to client struct
352 * output - pointer to struct Server
353 * side effects - add's an Server information block to a client
354 * if it was not previously allocated.
355 */
356 struct Server *
server_make(struct Client * client)357 server_make(struct Client *client)
358 {
359 if (client->serv == NULL)
360 client->serv = xcalloc(sizeof(*client->serv));
361
362 return client->serv;
363 }
364
365 /* server_connect() - initiate a server connection
366 *
367 * inputs - pointer to conf
368 * - pointer to client doing the connect
369 * output -
370 * side effects -
371 *
372 * This code initiates a connection to a server. It first checks to make
373 * sure the given server exists. If this is the case, it creates a socket,
374 * creates a client, saves the socket information in the client, and
375 * initiates a connection to the server through comm_connect_tcp(). The
376 * completion of this goes through serv_completed_connection().
377 *
378 * We return 1 if the connection is attempted, since we don't know whether
379 * it suceeded or not, and 0 if it fails in here somewhere.
380 */
381 bool
server_connect(struct MaskItem * conf,struct Client * by)382 server_connect(struct MaskItem *conf, struct Client *by)
383 {
384 char buf[HOSTIPLEN + 1];
385
386 /* Make sure conf is useful */
387 assert(conf);
388 assert(conf->type == CONF_SERVER);
389 assert(hash_find_server(conf->name) == NULL); /* This should have been checked by the caller */
390
391 /* Still processing a DNS lookup? -> exit */
392 if (conf->dns_pending == true)
393 {
394 sendto_realops_flags(UMODE_SERVNOTICE, L_ALL, SEND_NOTICE,
395 "Error connecting to %s: DNS lookup for connect{} in progress.",
396 conf->name);
397 return false;
398 }
399
400 if (conf->dns_failed == true)
401 {
402 sendto_realops_flags(UMODE_SERVNOTICE, L_ALL, SEND_NOTICE,
403 "Error connecting to %s: DNS lookup for connect{} failed.",
404 conf->name);
405 return false;
406 }
407
408 getnameinfo((const struct sockaddr *)conf->addr, conf->addr->ss_len,
409 buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
410 ilog(LOG_TYPE_IRCD, "Connect to %s[%s] @%s", conf->name, conf->host, buf);
411
412 /* Create a socket for the server connection */
413 int fd = comm_socket(conf->addr->ss.ss_family, SOCK_STREAM, 0);
414 if (fd == -1)
415 {
416 /* Eek, failure to create the socket */
417 report_error(L_ALL, "opening stream socket to %s: %s", conf->name, errno);
418 return false;
419 }
420
421 /* Create a local client */
422 struct Client *client = client_make(NULL);
423
424 /* Copy in the server, hostname, fd */
425 strlcpy(client->name, conf->name, sizeof(client->name));
426 strlcpy(client->host, conf->host, sizeof(client->host));
427
428 /* We already converted the ip once, so lets use it - stu */
429 strlcpy(client->sockhost, buf, sizeof(client->sockhost));
430
431 client->ip = *conf->addr;
432 client->connection->fd = fd_open(fd, true, NULL);
433
434 /* Server names are always guaranteed under HOSTLEN chars */
435 fd_note(client->connection->fd, "Server: %s", client->name);
436
437 /*
438 * Attach config entries to client here rather than in server_connect_callback().
439 * This to avoid null pointer references.
440 */
441 conf_attach(client, conf);
442
443 server_make(client);
444
445 if (by && IsClient(by))
446 strlcpy(client->serv->by, by->name, sizeof(client->serv->by));
447 else
448 strlcpy(client->serv->by, "AutoConn.", sizeof(client->serv->by));
449
450 SetConnecting(client);
451
452 /* Now, initiate the connection */
453 comm_connect_tcp(client->connection->fd, conf->addr, conf->port, conf->bind,
454 server_connect_callback, client, conf->timeout);
455
456 /*
457 * At this point we have a connection in progress and a connect {} block
458 * attached to the client, the socket info should be saved in the client
459 * and it should either be resolved or have a valid address.
460 *
461 * The socket has been connected or connect is in progress.
462 */
463 return true;
464 }
465
466 static void
server_finish_tls_handshake(struct Client * client)467 server_finish_tls_handshake(struct Client *client)
468 {
469 const struct MaskItem *conf = find_conf_name(&client->connection->confs,
470 client->name, CONF_SERVER);
471 if (conf == NULL)
472 {
473 sendto_realops_flags(UMODE_SERVNOTICE, L_ADMIN, SEND_NOTICE,
474 "Lost connect{} block for %s", client_get_name(client, SHOW_IP));
475 sendto_realops_flags(UMODE_SERVNOTICE, L_OPER, SEND_NOTICE,
476 "Lost connect{} block for %s", client_get_name(client, MASK_IP));
477
478 exit_client(client, "Lost connect{} block");
479 return;
480 }
481
482 /* Next, send the initial handshake */
483 SetHandshake(client);
484
485 sendto_one(client, "PASS %s", conf->spasswd);
486
487 sendto_one(client, "CAPAB :%s", capab_get(NULL));
488
489 sendto_one(client, "SERVER %s 1 %s +%s :%s",
490 me.name, me.id, ConfigServerHide.hidden ? "h" : "", me.info);
491
492 /* If we get here, we're ok, so lets start reading some data */
493 read_packet(client->connection->fd, client);
494 }
495
496 static void
server_tls_handshake(fde_t * F,void * data)497 server_tls_handshake(fde_t *F, void *data)
498 {
499 struct Client *client = data;
500 const char *sslerr = NULL;
501
502 assert(client);
503 assert(client->connection);
504 assert(client->connection->fd);
505 assert(client->connection->fd == F);
506
507 tls_handshake_status_t ret = tls_handshake(&F->tls, TLS_ROLE_CLIENT, &sslerr);
508 if (ret != TLS_HANDSHAKE_DONE)
509 {
510 if ((event_base->time.sec_monotonic - client->connection->created_monotonic) > TLS_HANDSHAKE_TIMEOUT)
511 {
512 exit_client(client, "Timeout during TLS handshake");
513 return;
514 }
515
516 switch (ret)
517 {
518 case TLS_HANDSHAKE_WANT_WRITE:
519 comm_setselect(F, COMM_SELECT_WRITE,
520 server_tls_handshake, client, TLS_HANDSHAKE_TIMEOUT);
521 return;
522 case TLS_HANDSHAKE_WANT_READ:
523 comm_setselect(F, COMM_SELECT_READ,
524 server_tls_handshake, client, TLS_HANDSHAKE_TIMEOUT);
525 return;
526 default:
527 {
528 sendto_realops_flags(UMODE_SERVNOTICE, L_ALL, SEND_NOTICE,
529 "Error connecting to %s: %s", client->name,
530 sslerr ? sslerr : "unknown TLS error");
531 exit_client(client, "Error during TLS handshake");
532 return;
533 }
534 }
535 }
536
537 comm_settimeout(F, 0, NULL, NULL);
538 comm_setselect(F, COMM_SELECT_WRITE | COMM_SELECT_READ, NULL, NULL, 0);
539
540 if (tls_verify_certificate(&F->tls, ConfigServerInfo.message_digest_algorithm, &client->tls_certfp) == false)
541 ilog(LOG_TYPE_IRCD, "Server %s gave bad TLS client certificate",
542 client_get_name(client, MASK_IP));
543
544 server_finish_tls_handshake(client);
545 }
546
547 static void
server_tls_connect_init(struct Client * client,const struct MaskItem * conf,fde_t * F)548 server_tls_connect_init(struct Client *client, const struct MaskItem *conf, fde_t *F)
549 {
550 assert(client);
551 assert(client->connection);
552 assert(client->connection->fd);
553 assert(client->connection->fd == F);
554
555 if (tls_new(&F->tls, F->fd, TLS_ROLE_CLIENT) == false)
556 {
557 SetDead(client);
558 exit_client(client, "TLS context initialization failed");
559 return;
560 }
561
562 if (!EmptyString(conf->cipher_list))
563 tls_set_ciphers(&F->tls, conf->cipher_list);
564
565 server_tls_handshake(F, client);
566 }
567
568 /* server_connect_callback() - complete a server connection.
569 *
570 * This routine is called after the server connection attempt has
571 * completed. If unsucessful, an error is sent to ops and the client
572 * is closed. If sucessful, it goes through the initialisation/check
573 * procedures, the capabilities are sent, and the socket is then
574 * marked for reading.
575 */
576 static void
server_connect_callback(fde_t * F,int status,void * data)577 server_connect_callback(fde_t *F, int status, void *data)
578 {
579 struct Client *const client = data;
580
581 /* First, make sure it's a real client! */
582 assert(client);
583 assert(client->connection);
584 assert(client->connection->fd);
585 assert(client->connection->fd == F);
586
587 /* Check the status */
588 if (status != COMM_OK)
589 {
590 /* We have an error, so report it and quit */
591 sendto_realops_flags(UMODE_SERVNOTICE, L_ADMIN, SEND_NOTICE,
592 "Error connecting to %s: %s",
593 client_get_name(client, SHOW_IP), comm_errstr(status));
594 sendto_realops_flags(UMODE_SERVNOTICE, L_OPER, SEND_NOTICE,
595 "Error connecting to %s: %s",
596 client_get_name(client, MASK_IP), comm_errstr(status));
597
598 /*
599 * If a fd goes bad, call dead_link() the socket is no
600 * longer valid for reading or writing.
601 */
602 dead_link_on_write(client, 0);
603 return;
604 }
605
606 /* COMM_OK, so continue the connection procedure */
607 /* Get the connect {} block */
608 const struct MaskItem *conf = find_conf_name(&client->connection->confs,
609 client->name, CONF_SERVER);
610 if (conf == NULL)
611 {
612 sendto_realops_flags(UMODE_SERVNOTICE, L_ADMIN, SEND_NOTICE,
613 "Lost connect{} block for %s", client_get_name(client, SHOW_IP));
614 sendto_realops_flags(UMODE_SERVNOTICE, L_OPER, SEND_NOTICE,
615 "Lost connect{} block for %s", client_get_name(client, MASK_IP));
616
617 exit_client(client, "Lost connect{} block");
618 return;
619 }
620
621 if (IsConfTLS(conf))
622 {
623 server_tls_connect_init(client, conf, F);
624 return;
625 }
626
627 /* Next, send the initial handshake */
628 SetHandshake(client);
629
630 sendto_one(client, "PASS %s", conf->spasswd);
631
632 sendto_one(client, "CAPAB :%s", capab_get(NULL));
633
634 sendto_one(client, "SERVER %s 1 %s +%s :%s",
635 me.name, me.id, ConfigServerHide.hidden ? "h" : "", me.info);
636
637 /* If we get here, we're ok, so lets start reading some data */
638 read_packet(client->connection->fd, client);
639 }
640
641 struct Client *
find_servconn_in_progress(const char * name)642 find_servconn_in_progress(const char *name)
643 {
644 dlink_node *ptr;
645
646 DLINK_FOREACH(ptr, unknown_list.head)
647 {
648 struct Client *cptr = ptr->data;
649
650 if (cptr->name[0])
651 if (!irccmp(name, cptr->name))
652 return cptr;
653 }
654
655 return NULL;
656 }
657