gdm-xdmcp-display-factory.c 107 KB
Newer Older
1
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * Copyright (C) 1998, 1999, 2000 Martin K. Petersen <mkp@mkp.net>
 * Copyright (C) 2007 William Jon McCann <mccann@jhu.edu>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>

#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
37 38 39 40
#include <net/if.h>
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
41
#include <sys/ioctl.h>
42 43 44 45 46 47 48 49 50 51 52 53

#include <errno.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <glib-object.h>

#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/Xdmcp.h>

#include "gdm-common.h"
54
#include "gdm-xdmcp-display.h"
55 56
#include "gdm-display-factory.h"
#include "gdm-xdmcp-display-factory.h"
57
#include "gdm-display-store.h"
58 59 60 61 62 63 64 65 66 67 68 69 70

#include "auth.h"

/*
 * On Sun, we need to define allow_severity and deny_severity to link
 * against libwrap.
 */
#ifdef __sun
#include <syslog.h>
int allow_severity = LOG_INFO;
int deny_severity = LOG_WARNING;
#endif

71
#define GDM_XDMCP_DISPLAY_FACTORY_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GDM_TYPE_XDMCP_DISPLAY_FACTORY, GdmXdmcpDisplayFactoryPrivate))
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

#define DEFAULT_PORT                  177
#define DEFAULT_USE_MULTICAST         FALSE
#define DEFAULT_MULTICAST_ADDRESS     "ff02::1"
#define DEFAULT_HONOR_INDIRECT        TRUE
#define DEFAULT_MAX_DISPLAYS_PER_HOST 2
#define DEFAULT_MAX_DISPLAYS          16
#define DEFAULT_MAX_PENDING_DISPLAYS  4
#define DEFAULT_MAX_WAIT              15

#define GDM_MAX_FORWARD_QUERIES 10
#define GDM_FORWARD_QUERY_TIMEOUT 30
#define MANAGED_FORWARD_INTERVAL 1500 /* 1.5 seconds */

/* some extra XDMCP opcodes that xdm will happily ignore since they'll be
 * the wrong XDMCP version anyway */
#define GDM_XDMCP_PROTOCOL_VERSION 1001
enum {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        GDM_XDMCP_FIRST_OPCODE = 1000, /*just a marker, not an opcode */

        GDM_XDMCP_MANAGED_FORWARD = 1000,
                /* manager (master) -> manager
                 * A packet with MANAGED_FORWARD is sent to the
                 * manager that sent the forward query from the manager to
                 * which forward query was sent.  It indicates that the forward
                 * was fully processed and that the client now has either
                 * a managed session, or has been sent denial, refuse or failed.
                 * (if the denial gets lost then client gets dumped into the
                 * chooser again).  This should be resent a few times
                 * until some (short) timeout or until GOT_MANAGED_FORWARD
                 * is sent.  GDM sends at most 3 packates with 1.5 seconds
                 * between each.
                 *
                 * Argument is ARRAY8 with the address of the originating host */
        GDM_XDMCP_GOT_MANAGED_FORWARD,
                /* manager -> manager (master)
                 * A single packet with GOT_MANAGED_FORWARD is sent to indicate
                 * that we did receive the MANAGED_FORWARD packet.  The argument
                 * must match the MANAGED_FORWARD one or it will just be ignored.
                 *
                 * Argument is ARRAY8 with the address of the originating host */
        GDM_XDMCP_LAST_OPCODE /*just a marker, not an opcode */
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
};

/*
 * We don't support XDM-AUTHENTICATION-1 and XDM-AUTHORIZATION-1.
 *
 * The latter would be quite useful to avoid sending unencrypted
 * cookies over the wire. Unfortunately it isn't supported without
 * XDM-AUTHENTICATION-1 which requires a key database with private
 * keys from all X terminals on your LAN. Fun, fun, fun.
 *
 * Furthermore user passwords go over the wire in cleartext anyway,
 * so protecting cookies is not that important.
 */

typedef struct _XdmAuth {
129 130
        ARRAY8 authentication;
        ARRAY8 authorization;
131 132 133
} XdmAuthRec, *XdmAuthPtr;

static XdmAuthRec serv_authlist = {
134 135
        { (CARD16) 0, (CARD8 *) 0 },
        { (CARD16) 0, (CARD8 *) 0 }
136 137 138 139
};

/* NOTE: Timeout and max are hardcoded */
typedef struct _GdmForwardQuery {
140 141 142
        time_t      acctime;
        GdmAddress *dsp_address;
        GdmAddress *from_address;
143 144 145
} GdmForwardQuery;

typedef struct {
146 147 148 149 150
        int              times;
        guint            handler;
        GdmAddress      *manager;
        GdmAddress      *origin;
        GdmXdmcpDisplayFactory *xdmcp_display_factory;
151 152
} ManagedForward;

153
struct GdmXdmcpDisplayFactoryPrivate
154
{
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        GSList          *forward_queries;
        GSList          *managed_forwards;

        int              socket_fd;
        gint32           session_serial;
        guint            socket_watch_id;
        XdmcpBuffer      buf;

        guint            num_sessions;
        guint            num_pending_sessions;

        char            *sysid;
        char            *hostname;
        ARRAY8           servhost;

        /* configuration */
        guint            port;
        gboolean         use_multicast;
        char            *multicast_address;
        gboolean         honor_indirect;
        char            *willing_script;
        guint            max_displays_per_host;
        guint            max_displays;
        guint            max_pending_displays;
        guint            max_wait;
180 181 182
};

enum {
183 184 185 186 187 188 189 190 191 192
        PROP_0,
        PROP_PORT,
        PROP_USE_MULTICAST,
        PROP_MULTICAST_ADDRESS,
        PROP_HONOR_INDIRECT,
        PROP_WILLING_SCRIPT,
        PROP_MAX_DISPLAYS_PER_HOST,
        PROP_MAX_DISPLAYS,
        PROP_MAX_PENDING_DISPLAYS,
        PROP_MAX_WAIT,
193 194
};

195 196 197
static void     gdm_xdmcp_display_factory_class_init    (GdmXdmcpDisplayFactoryClass *klass);
static void     gdm_xdmcp_display_factory_init          (GdmXdmcpDisplayFactory      *manager);
static void     gdm_xdmcp_display_factory_finalize      (GObject              *object);
198

199
static gpointer xdmcp_display_factory_object = NULL;
200

William Jon McCann's avatar
William Jon McCann committed
201
G_DEFINE_TYPE (GdmXdmcpDisplayFactory, gdm_xdmcp_display_factory, GDM_TYPE_DISPLAY_FACTORY)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237

/* Theory of operation:
 *
 * Process idles waiting for UDP packets on port 177.
 * Incoming packets are decoded and checked against tcp_wrapper.
 *
 * A typical session looks like this:
 *
 * Display sends Query/BroadcastQuery to Manager.
 *
 * Manager selects an appropriate authentication scheme from the
 * display's list of supported ones and sends Willing/Unwilling.
 *
 * Assuming the display accepts the auth. scheme it sends back a
 * Request.
 *
 * If the manager accepts to service the display (i.e. loadavg is low)
 * it sends back an Accept containing a unique SessionID. The
 * SessionID is stored in an accept queue by the Manager. Should the
 * manager refuse to start a session a Decline is sent to the display.
 *
 * The display returns a Manage request containing the supplied
 * SessionID. The manager will then start a session on the display. In
 * case the SessionID is not on the accept queue the manager returns
 * Refuse. If the manager fails to open the display for connections
 * Failed is returned.
 *
 * During the session the display periodically sends KeepAlive packets
 * to the manager. The manager responds with Alive.
 *
 * Similarly the manager xpings the display once in a while and shuts
 * down the connection on failure.
 *
 */

GQuark
238
gdm_xdmcp_display_factory_error_quark (void)
239
{
240 241 242 243
        static GQuark ret = 0;
        if (ret == 0) {
                ret = g_quark_from_static_string ("gdm_xdmcp_display_factory_error");
        }
244

245
        return ret;
246 247 248
}

static gint32
249
get_next_session_serial (GdmXdmcpDisplayFactory *factory)
250
{
251
        gint32 serial;
252 253

 again:
254 255 256 257 258
        if (factory->priv->session_serial != G_MAXINT32) {
                serial = factory->priv->session_serial++;
        } else {
                serial = g_random_int ();
        }
259

260 261 262
        if (serial == 0) {
                goto again;
        }
263

264
        return serial;
265 266 267 268 269 270
}

/* for debugging */
static const char *
ai_family_str (struct addrinfo *ai)
{
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        const char *str;
        switch (ai->ai_family) {
        case AF_INET:
                str = "inet";
                break;
        case AF_INET6:
                str = "inet6";
                break;
        case AF_UNIX:
                str = "unix";
                break;
        case AF_UNSPEC:
                str = "unspecified";
                break;
        default:
                str = "unknown";
                break;
        }
        return str;
290 291 292 293 294 295
}

/* for debugging */
static const char *
ai_type_str (struct addrinfo *ai)
{
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        const char *str;
        switch (ai->ai_socktype) {
        case SOCK_STREAM:
                str = "stream";
                break;
        case SOCK_DGRAM:
                str = "datagram";
                break;
        case SOCK_SEQPACKET:
                str = "seqpacket";
                break;
        case SOCK_RAW:
                str = "raw";
                break;
        default:
                str = "unknown";
                break;
        }
        return str;
315 316 317 318 319 320
}

/* for debugging */
static const char *
ai_protocol_str (struct addrinfo *ai)
{
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        const char *str;
        switch (ai->ai_protocol) {
        case 0:
                str = "default";
                break;
        case IPPROTO_TCP:
                str = "TCP";
                break;
        case IPPROTO_UDP:
                str = "UDP";
                break;
        case IPPROTO_RAW:
                str = "raw";
                break;
        default:
                str = "unknown";
                break;
        }

        return str;
341 342 343 344 345 346
}

/* for debugging */
static char *
ai_flags_str (struct addrinfo *ai)
{
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        GString *str;

        str = g_string_new ("");
        if (ai->ai_flags == 0) {
                g_string_append (str, "none");
        } else {
                if (ai->ai_flags & AI_PASSIVE) {
                        g_string_append (str, "passive ");
                }
                if (ai->ai_flags & AI_CANONNAME) {
                        g_string_append (str, "canon ");
                }
                if (ai->ai_flags & AI_NUMERICHOST) {
                        g_string_append (str, "numhost ");
                }
                if (ai->ai_flags & AI_NUMERICSERV) {
                        g_string_append (str, "numserv ");
                }
                if (ai->ai_flags & AI_V4MAPPED) {
                        g_string_append (str, "v4mapped ");
                }
                if (ai->ai_flags & AI_ALL) {
                        g_string_append (str, "all ");
                }
        }
        return g_string_free (str, FALSE);
373 374 375 376 377 378
}

/* for debugging */
static void
debug_addrinfo (struct addrinfo *ai)
{
379 380 381 382 383 384 385 386
        char *str;
        str = ai_flags_str (ai);
        g_debug ("XDMCP: addrinfo family=%s type=%s proto=%s flags=%s",
                 ai_family_str (ai),
                 ai_type_str (ai),
                 ai_protocol_str (ai),
                 str);
        g_free (str);
387 388 389 390 391
}

static int
create_socket (struct addrinfo *ai)
{
392
        int sock;
393

394 395 396 397 398
        sock = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (sock < 0) {
                g_warning ("socket: %s", g_strerror (errno));
                return sock;
        }
399

400 401 402 403 404
        if (bind (sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                g_warning ("bind: %s", g_strerror (errno));
                close (sock);
                return -1;
        }
405

406
        return sock;
407 408 409 410
}

static int
do_bind (guint                     port,
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
         int                       family,
         struct sockaddr_storage * hostaddr)
{
        struct addrinfo  hints;
        struct addrinfo *ai_list;
        struct addrinfo *ai;
        char             strport[NI_MAXSERV];
        int              gaierr;
        int              sock;

        sock = -1;

        memset (&hints, 0, sizeof (hints));
        hints.ai_family = family;
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_flags = AI_PASSIVE;

        snprintf (strport, sizeof (strport), "%u", port);
429 430

        ai_list = NULL;
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        if ((gaierr = getaddrinfo (NULL, strport, &hints, &ai_list)) != 0) {
                g_error ("Unable to connect to socket: %s", gai_strerror (gaierr));
                return -1;
        }

        /* should only be one but.. */
        for (ai = ai_list; ai != NULL; ai = ai->ai_next) {
                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) {
                        continue;
                }

                debug_addrinfo (ai);

                if (sock < 0) {
                        char       *host;
                        char       *serv;
                        GdmAddress *addr;

                        addr = gdm_address_new_from_sockaddr_storage ((struct sockaddr_storage *)ai->ai_addr);

                        host = NULL;
                        serv = NULL;
                        gdm_address_get_numeric_info (addr, &host, &serv);
                        g_debug ("XDMCP: Attempting to bind to host %s port %s", host, serv);
                        g_free (host);
                        g_free (serv);
                        gdm_address_free (addr);

                        sock = create_socket (ai);
                        if (sock >= 0) {
                                if (hostaddr != NULL) {
                                        memcpy (hostaddr, ai->ai_addr, ai->ai_addrlen);
                                }
                        }
                }
        }

        freeaddrinfo (ai_list);

        return sock;
471 472 473
}

static void
474
setup_multicast (GdmXdmcpDisplayFactory *factory)
475 476
{
#ifdef ENABLE_IPV6
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        /* Checking and Setting Multicast options */
        {
                /*
                 * socktemp is a temporary socket for getting info about
                 * available interfaces
                 */
                int              socktemp;
                int              i;
                int              num;
                char            *buf;
                struct ipv6_mreq mreq;

                /* For interfaces' list */
                struct ifconf    ifc;
                struct ifreq    *ifr;

                socktemp = socket (AF_INET, SOCK_DGRAM, 0);
494
#ifdef SIOCGIFNUM
495 496 497
                if (ioctl (socktemp, SIOCGIFNUM, &num) < 0) {
                        num = 64;
                }
498
#else
499
                num = 64;
500
#endif /* SIOCGIFNUM */
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
                ifc.ifc_len = sizeof (struct ifreq) * num;
                ifc.ifc_buf = buf = malloc (ifc.ifc_len);

                if (ioctl (socktemp, SIOCGIFCONF, &ifc) >= 0) {
                        ifr = ifc.ifc_req;
                        num = ifc.ifc_len / sizeof (struct ifreq); /* No of interfaces */

                        /* Joining multicast group with all interfaces */
                        for (i = 0 ; i < num ; i++) {
                                struct ifreq ifreq;
                                int          ifindex;

                                memset (&ifreq, 0, sizeof (ifreq));
                                strncpy (ifreq.ifr_name, ifr[i].ifr_name, sizeof (ifreq.ifr_name));
                                /* paranoia */
                                ifreq.ifr_name[sizeof (ifreq.ifr_name) - 1] = '\0';

                                if (ioctl (socktemp, SIOCGIFFLAGS, &ifreq) < 0) {
                                        g_debug ("XDMCP: Could not get SIOCGIFFLAGS for %s",
                                                 ifr[i].ifr_name);
                                }

                                ifindex = if_nametoindex (ifr[i].ifr_name);

                                if ((!(ifreq.ifr_flags & IFF_UP) ||
                                     (ifreq.ifr_flags & IFF_LOOPBACK)) ||
                                    ((ifindex == 0 ) && (errno == ENXIO))) {
                                        /* Not a valid interface or loopback interface*/
                                        continue;
                                }

                                mreq.ipv6mr_interface = ifindex;
                                inet_pton (AF_INET6,
                                           factory->priv->multicast_address,
                                           &mreq.ipv6mr_multiaddr);

                                setsockopt (factory->priv->socket_fd,
                                            IPPROTO_IPV6,
                                            IPV6_JOIN_GROUP,
                                            &mreq,
                                            sizeof (mreq));
                        }
                }
                g_free (buf);
                close (socktemp);
        }
547 548 549
#endif /* ENABLE_IPV6 */
}

550
static void
551 552 553 554 555 556 557 558 559 560 561 562 563 564
fd_set_close_on_exec (int fd)
{
        int flags;

        flags = fcntl (fd, F_GETFD, 0);
        if (flags < 0) {
                return;
        }

        flags |= FD_CLOEXEC;

        fcntl (fd, F_SETFD, flags);
}

565
static gboolean
566
open_port (GdmXdmcpDisplayFactory *factory)
567
{
568
        struct sockaddr_storage serv_sa = { 0 };
569

570 571 572
        g_debug ("XDMCP: Start up on host %s, port %d",
                 factory->priv->hostname,
                 factory->priv->port);
573

574
        /* Open socket for communications */
575
#ifdef ENABLE_IPV6
576 577
        factory->priv->socket_fd = do_bind (factory->priv->port, AF_INET6, &serv_sa);
        if (factory->priv->socket_fd < 0)
578
#endif
579
                factory->priv->socket_fd = do_bind (factory->priv->port, AF_INET, &serv_sa);
580

581 582 583 584
        if G_UNLIKELY (factory->priv->socket_fd < 0) {
                g_warning (_("Could not create socket!"));
                return FALSE;
        }
585

586
        fd_set_close_on_exec (factory->priv->socket_fd);
587

588 589 590
        if (factory->priv->use_multicast) {
                setup_multicast (factory);
        }
591

592
        return TRUE;
593 594 595
}

static gboolean
596
gdm_xdmcp_host_allow (GdmAddress *address)
597 598 599
{
#ifdef HAVE_TCPWRAPPERS

600 601 602 603 604 605 606 607
        /*
         * Avoids a warning, my tcpd.h file doesn't include this prototype, even
         * though the library does include the function and the manpage mentions it
         */
        extern int hosts_ctl (char *daemon,
                              char *client_name,
                              char *client_addr,
                              char *client_user);
608

609 610 611
        char       *client;
        char       *host;
        gboolean    ret;
612

613 614
        host = NULL;
        client = NULL;
615

616 617 618
        /* Find client hostname */
        gdm_address_get_hostname (address, &client);
        gdm_address_get_numeric_info (address, &host, NULL);
619

620 621
        /* Check with tcp_wrappers if client is allowed to access */
        ret = hosts_ctl ("gdm", client, host, "");
622

623 624
        g_free (host);
        g_free (client);
625

626
        return ret;
627
#else /* HAVE_TCPWRAPPERS */
628
        return (TRUE);
629 630 631
#endif /* HAVE_TCPWRAPPERS */
}

632
typedef struct {
633 634
        GdmAddress *address;
        int         count;
635 636 637 638
} CountDisplayData;

static gboolean
count_displays_from_host (const char       *id,
639 640
                          GdmDisplay       *display,
                          CountDisplayData *data)
641
{
642
        GdmAddress *address;
643

644 645
        if (GDM_IS_XDMCP_DISPLAY (display)) {
                address = gdm_xdmcp_display_get_remote_address (GDM_XDMCP_DISPLAY (display));
646

647 648 649 650
                if (gdm_address_equal (address, data->address)) {
                        data->count++;
                }
        }
651

652
        return TRUE;
653 654
}

655
static int
656
gdm_xdmcp_num_displays_from_host (GdmXdmcpDisplayFactory *factory,
657
                                  GdmAddress             *address)
658
{
659 660
        CountDisplayData data;
        GdmDisplayStore *store;
661

662 663
        data.count = 0;
        data.address = address;
664

665 666 667 668
        store = gdm_display_factory_get_display_store (GDM_DISPLAY_FACTORY (factory));
        gdm_display_store_foreach (store,
                                   (GdmDisplayStoreFunc)count_displays_from_host,
                                   &data);
669

670
        return data.count;
671 672 673
}

typedef struct {
674 675
        GdmAddress *address;
        int         display_num;
676 677 678 679
} LookupHostData;

static gboolean
lookup_by_host (const char     *id,
680 681
                GdmDisplay     *display,
                LookupHostData *data)
682
{
683 684
        GdmAddress *this_address;
        int         disp_num;
685

686 687 688
        if (! GDM_IS_XDMCP_DISPLAY (display)) {
                return FALSE;
        }
689

690 691
        this_address = gdm_xdmcp_display_get_remote_address (GDM_XDMCP_DISPLAY (display));
        gdm_display_get_x11_display_number (display, &disp_num, NULL);
692

693 694 695 696
        if (gdm_address_equal (this_address, data->address)
            && disp_num == data->display_num) {
                return TRUE;
        }
697

698
        return FALSE;
699 700 701
}

static GdmDisplay *
702
gdm_xdmcp_display_lookup_by_host (GdmXdmcpDisplayFactory *factory,
703 704
                                  GdmAddress      *address,
                                  int              display_num)
705
{
706 707 708
        GdmDisplay      *display;
        LookupHostData  *data;
        GdmDisplayStore *store;
709

710 711 712
        data = g_new0 (LookupHostData, 1);
        data->address = address;
        data->display_num = display_num;
713

714 715 716 717 718
        store = gdm_display_factory_get_display_store (GDM_DISPLAY_FACTORY (factory));
        display = gdm_display_store_find (store,
                                          (GdmDisplayStoreFunc)lookup_by_host,
                                          data);
        g_free (data);
719

720
        return display;
721 722 723
}

static char *
724
get_willing_output (GdmXdmcpDisplayFactory *factory)
725
{
726 727 728 729
        char  *output;
        char **argv;
        FILE  *fd;
        char   buf[256];
730

731 732
        output = NULL;
        buf[0] = '\0';
733

734 735 736
        if (factory->priv->willing_script == NULL) {
                goto out;
        }
737

738 739 740 741
        argv = NULL;
        if (! g_shell_parse_argv (factory->priv->willing_script, NULL, &argv, NULL)) {
                goto out;
        }
742

743 744 745 746 747
        if (argv == NULL ||
            argv[0] == NULL ||
            g_access (argv[0], X_OK) != 0) {
                goto out;
        }
748

749 750 751 752
        fd = popen (factory->priv->willing_script, "r");
        if (fd == NULL) {
                goto out;
        }
753

754 755 756 757
        if (fgets (buf, sizeof (buf), fd) == NULL) {
                pclose (fd);
                goto out;
        }
758

759
        pclose (fd);
760

761
        output = g_strdup (buf);
762 763

 out:
764
        return output;
765 766 767
}

static void
768
gdm_xdmcp_send_willing (GdmXdmcpDisplayFactory *factory,
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
                        GdmAddress      *address)
{
        ARRAY8        status;
        XdmcpHeader   header;
        static char  *last_status = NULL;
        static time_t last_willing = 0;
        char         *host;

        host = NULL;
        gdm_address_get_numeric_info (address, &host, NULL);
        g_debug ("XDMCP: Sending WILLING to %s", host);
        g_free (host);

        if (last_willing == 0 || time (NULL) - 3 > last_willing) {
                char *s;

                g_free (last_status);

                s = get_willing_output (factory);
                if (s != NULL) {
                        g_free (last_status);
                        last_status = s;
                } else {
                        last_status = g_strdup (factory->priv->sysid);
                }
        }

        if (! gdm_address_is_local (address) &&
            gdm_xdmcp_num_displays_from_host (factory, address) >= factory->priv->max_displays_per_host) {
                /*
                 * Don't translate, this goes over the wire to servers where we
                 * don't know the charset or language, so it must be ascii
                 */
                status.data = (CARD8 *) g_strdup_printf ("%s (Server is busy)",
                                                         last_status);
        } else {
                status.data = (CARD8 *) g_strdup (last_status);
        }

        status.length = strlen ((char *) status.data);

        header.opcode   = (CARD16) WILLING;
        header.length   = 6 + serv_authlist.authentication.length;
        header.length  += factory->priv->servhost.length + status.length;
        header.version  = XDM_PROTOCOL_VERSION;
        XdmcpWriteHeader (&factory->priv->buf, &header);

        /* Hardcoded authentication */
        XdmcpWriteARRAY8 (&factory->priv->buf, &serv_authlist.authentication);
        XdmcpWriteARRAY8 (&factory->priv->buf, &factory->priv->servhost);
        XdmcpWriteARRAY8 (&factory->priv->buf, &status);

        XdmcpFlush (factory->priv->socket_fd,
                    &factory->priv->buf,
                    (XdmcpNetaddr)gdm_address_peek_sockaddr_storage (address),
                    (int)sizeof (struct sockaddr_storage));

        g_free (status.data);
827 828 829
}

static void
830
gdm_xdmcp_send_unwilling (GdmXdmcpDisplayFactory *factory,
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
                          GdmAddress      *address,
                          int              type)
{
        ARRAY8        status;
        XdmcpHeader   header;
        static time_t last_time = 0;
        char         *host;

        /* only send at most one packet per second,
           no harm done if we don't send it at all */
        if (last_time + 1 >= time (NULL)) {
                return;
        }

        host = NULL;
        gdm_address_get_numeric_info (address, &host, NULL);
        g_debug ("XDMCP: Sending UNWILLING to %s", host);
        g_warning (_("Denied XDMCP query from host %s"), host);
        g_free (host);

        /*
         * Don't translate, this goes over the wire to servers where we
         * don't know the charset or language, so it must be ascii
         */
        status.data = (CARD8 *) "Display not authorized to connect";
        status.length = strlen ((char *) status.data);

        header.opcode = (CARD16) UNWILLING;
        header.length = 4 + factory->priv->servhost.length + status.length;
        header.version = XDM_PROTOCOL_VERSION;
        XdmcpWriteHeader (&factory->priv->buf, &header);

        XdmcpWriteARRAY8 (&factory->priv->buf, &factory->priv->servhost);
        XdmcpWriteARRAY8 (&factory->priv->buf, &status);
        XdmcpFlush (factory->priv->socket_fd,
                    &factory->priv->buf,
                    (XdmcpNetaddr)gdm_address_peek_sockaddr_storage (address),
                    (int)sizeof (struct sockaddr_storage));

        last_time = time (NULL);
871 872 873 874 875 876
}

#define SIN(__s)   ((struct sockaddr_in *) __s)
#define SIN6(__s)  ((struct sockaddr_in6 *) __s)

static void
877
set_port_for_request (GdmAddress *address,
878
                      ARRAY8     *port)
879
{
880
        struct sockaddr_storage *ss;
881

882
        ss = gdm_address_peek_sockaddr_storage (address);
883

884 885
        /* we depend on this being 2 elsewhere as well */
        port->length = 2;
886

887 888 889 890 891 892 893 894 895 896 897
        switch (ss->ss_family) {
        case AF_INET:
                port->data = (CARD8 *)g_memdup (&(SIN (ss)->sin_port), port->length);
                break;
        case AF_INET6:
                port->data = (CARD8 *)g_memdup (&(SIN6 (ss)->sin6_port), port->length);
                break;
        default:
                port->data = NULL;
                break;
        }
898 899 900
}

static void
901
set_address_for_request (GdmAddress *address,
902
                         ARRAY8     *addr)
903
{
904
        struct sockaddr_storage *ss;
905

906
        ss = gdm_address_peek_sockaddr_storage (address);
907

908 909 910 911 912 913 914 915 916 917 918 919 920 921
        switch (ss->ss_family) {
        case AF_INET:
                addr->length = sizeof (struct in_addr);
                addr->data = g_memdup (&SIN (ss)->sin_addr, addr->length);
                break;
        case AF_INET6:
                addr->length = sizeof (struct in6_addr);
                addr->data = g_memdup (&SIN6 (ss)->sin6_addr, addr->length);
                break;
        default:
                addr->length = 0;
                addr->data = NULL;
                break;
        }
922 923 924

}

925 926
#if 0
/* FIXME: Add chooser support */
927
static void
928
gdm_xdmcp_send_forward_query (GdmXdmcpDisplayFactory  *factory,
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
                              GdmIndirectDisplay      *id,
                              GdmAddress              *address,
                              GdmAddress              *display_address,
                              ARRAYofARRAY8Ptr         authlist)
{
        XdmcpHeader              header;
        int                      i;
        ARRAY8                   addr;
        ARRAY8                   port;
        char                    *host;
        char                    *serv;

        g_assert (id != NULL);
        g_assert (id->chosen_host != NULL);

        host = NULL;
        gdm_address_get_numeric_info (id->chosen_host, &host, NULL);
        g_debug ("XDMCP: Sending forward query to %s",
                   host);
        g_free (host);

        host = NULL;
        serv = NULL;
        gdm_address_get_numeric_info (display_address, &host, &serv);
        g_debug ("gdm_xdmcp_send_forward_query: Query contains %s:%s",
                 host, serv);
        g_free (host);
        g_free (serv);

        set_port_for_request (address, &port);
        set_address_for_request (display_address, &addr);

        header.version = XDM_PROTOCOL_VERSION;
        header.opcode = (CARD16) FORWARD_QUERY;
        header.length = 0;
        header.length += 2 + addr.length;
        header.length += 2 + port.length;
        header.length += 1;
        for (i = 0; i < authlist->length; i++) {
                header.length += 2 + authlist->data[i].length;
        }

        XdmcpWriteHeader (&factory->priv->buf, &header);
        XdmcpWriteARRAY8 (&factory->priv->buf, &addr);
        XdmcpWriteARRAY8 (&factory->priv->buf, &port);
        XdmcpWriteARRAYofARRAY8 (&factory->priv->buf, authlist);

        XdmcpFlush (factory->priv->socket_fd,
                    &factory->priv->buf,
                    (XdmcpNetaddr)gdm_address_peek_sockaddr_storage (id->chosen_host),
                    (int)sizeof (struct sockaddr_storage));

        g_free (port.data);
        g_free (addr.data);
983
}
984
#endif
985 986

static void
987
handle_any_query (GdmXdmcpDisplayFactory         *factory,
988 989 990
                  GdmAddress              *address,
                  ARRAYofARRAY8Ptr         authentication_names,
                  int                      type)
991
{
992
        gdm_xdmcp_send_willing (factory, address);
993 994 995
}

static void
996
handle_direct_query (GdmXdmcpDisplayFactory         *factory,
997 998 999
                     GdmAddress              *address,
                     int                      len,
                     int                      type)
1000
{
1001 1002 1003 1004
        ARRAYofARRAY8 clnt_authlist;
        int           expected_len;
        int           i;
        int           res;
1005

1006 1007 1008 1009 1010
        res = XdmcpReadARRAYofARRAY8 (&factory->priv->buf, &clnt_authlist);
        if G_UNLIKELY (! res) {
                g_warning (_("Could not extract authlist from packet"));
                return;
        }
1011

1012
        expected_len = 1;
1013

1014 1015 1016
        for (i = 0 ; i < clnt_authlist.length ; i++) {
                expected_len += 2 + clnt_authlist.data[i].length;
        }
1017

1018 1019 1020 1021 1022
        if (len == expected_len) {
                handle_any_query (factory, address, &clnt_authlist, type);
        } else {
                g_warning (_("Error in checksum"));
        }
1023

1024
        XdmcpDisposeARRAYofARRAY8 (&clnt_authlist);
1025 1026 1027
}

static void
1028
gdm_xdmcp_handle_broadcast_query (GdmXdmcpDisplayFactory *factory,
1029 1030
                                  GdmAddress      *address,
                                  int              len)
1031
{
1032 1033 1034 1035 1036
        if (gdm_xdmcp_host_allow (address)) {
                handle_direct_query (factory, address, len, BROADCAST_QUERY);
        } else {
                /* just ignore it */
        }
1037 1038 1039
}

static void
1040
gdm_xdmcp_handle_query (GdmXdmcpDisplayFactory *factory,
1041 1042
                        GdmAddress      *address,
                        int              len)
1043
{
1044 1045 1046 1047 1048
        if (gdm_xdmcp_host_allow (address)) {
                handle_direct_query (factory, address, len, QUERY);
        } else {
                gdm_xdmcp_send_unwilling (factory, address, QUERY);
        }
1049 1050 1051
}

static void
1052
gdm_xdmcp_handle_indirect_query (GdmXdmcpDisplayFactory *factory,
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
                                 GdmAddress      *address,
                                 int              len)
{
        ARRAYofARRAY8       clnt_authlist;
        int                 expected_len;
        int                 i;
        int                 res;

        if (! gdm_xdmcp_host_allow (address)) {
                /* ignore the request */
                return;
        }

        if (! factory->priv->honor_indirect) {
                /* ignore it */
                return;
        }

        res = XdmcpReadARRAYofARRAY8 (&factory->priv->buf, &clnt_authlist);
        if G_UNLIKELY (! res) {
                g_warning (_("Could not extract authlist from packet"));
                return;
        }

        expected_len = 1;

        for (i = 0 ; i < clnt_authlist.length ; i++) {
                expected_len += 2 + clnt_authlist.data[i].length;
        }

        /* Try to look up the display in
         * the pending list. If found send a FORWARD_QUERY to the
         * chosen factory. Otherwise alloc a new indirect display. */

        if (len != expected_len) {
                g_warning (_("Error in checksum"));
                goto out;
        }


1093
#if 0
1094
        GdmIndirectDisplay *id;
1095 1096
        /* FIXME: Add chooser support */

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
        id = gdm_choose_indirect_lookup (address);

        if (id != NULL && id->chosen_host != NULL) {
                /* if user chose us, then just send willing */
                if (gdm_address_is_local (id->chosen_host)) {
                        /* get rid of indirect, so that we don't get
                         * the chooser */
                        gdm_choose_indirect_dispose (id);
                        gdm_xdmcp_send_willing (factory, address);
                } else if (gdm_address_is_loopback (address)) {
                        /* woohoo! fun, I have no clue how to get
                         * the correct ip, SO I just send forward
                         * queries with all the different IPs */
                        const GList *list = gdm_address_peek_local_list ();

                        while (list != NULL) {
                                GdmAddress *saddr = list->data;

                                if (! gdm_address_is_loopback (saddr)) {
                                        /* forward query to * chosen host */
                                        gdm_xdmcp_send_forward_query (factory,
                                                                      id,
                                                                      address,
                                                                      saddr,
                                                                      &clnt_authlist);
                                }

                                list = list->next;
                        }
                } else {
                        /* or send forward query to chosen host */
                        gdm_xdmcp_send_forward_query (factory,
                                                      id,
                                                      address,
                                                      address,
                                                      &clnt_authlist);
                }
        } else if (id == NULL) {
                id = gdm_choose_indirect_alloc (address);
                if (id != NULL) {
                        gdm_xdmcp_send_willing (factory, address);
                }
        } else  {
                gdm_xdmcp_send_willing (factory, address);
        }
1142
#endif
1143

1144
out:
1145
        XdmcpDisposeARRAYofARRAY8 (&clnt_authlist);
1146 1147 1148
}

static void
1149
gdm_forward_query_dispose (GdmXdmcpDisplayFactory *factory,
1150
                           GdmForwardQuery *q)
1151
{
1152 1153 1154
        if (q == NULL) {
                return;
        }
1155

1156
        factory->priv->forward_queries = g_slist_remove (factory->priv->forward_queries, q);
1157

1158
        q->acctime = 0;
1159

1160 1161
        {
                char *host;
1162

1163 1164 1165 1166 1167
                host = NULL;
                gdm_address_get_numeric_info (q->dsp_address, &host, NULL);
                g_debug ("gdm_forward_query_dispose: Disposing %s", host);
                g_free (host);
        }
1168

1169 1170 1171 1172
        g_free (q->dsp_address);
        q->dsp_address = NULL;
        g_free (q->from_address);
        q->from_address = NULL;
1173

1174
        g_free (q);
1175 1176 1177
}

static gboolean
1178
remove_oldest_forward (GdmXdmcpDisplayFactory *factory)
1179
{
1180 1181
        GSList          *li;
        GdmForwardQuery *oldest = NULL;
1182

1183 1184
        for (li = factory->priv->forward_queries; li != NULL; li = li->next) {
                GdmForwardQuery *query = li->data;
1185

1186 1187 1188 1189
                if (oldest == NULL || query->acctime < oldest->acctime) {
                        oldest = query;
                }
        }
1190

1191 1192 1193 1194 1195 1196
        if (oldest != NULL) {
                gdm_forward_query_dispose (factory, oldest);
                return TRUE;
        } else {
                return FALSE;
        }
1197 1198 1199
}

static GdmForwardQuery *
1200
gdm_forward_query_alloc (GdmXdmcpDisplayFactory *factory,
1201 1202
                         GdmAddress      *mgr_address,
                         GdmAddress      *dsp_address)
1203
{
1204 1205
        GdmForwardQuery *q;
        int              count;
1206

1207
        count = g_slist_length (factory->priv->forward_queries);
1208

1209 1210 1211
        while (count > GDM_MAX_FORWARD_QUERIES && remove_oldest_forward (factory)) {
                count--;
        }
1212

1213 1214 1215
        q = g_new0 (GdmForwardQuery, 1);
        q->dsp_address = gdm_address_copy (dsp_address);
        q->from_address = gdm_address_copy (mgr_address);
1216

1217
        factory->priv->forward_queries = g_slist_prepend (factory->priv->forward_queries, q);
1218

1219
        return q;
1220 1221 1222
}

static GdmForwardQuery *
1223
gdm_forward_query_lookup (GdmXdmcpDisplayFactory *factory,
1224
                          GdmAddress      *address)
1225
{
1226 1227 1228 1229
        GSList          *li;
        GSList          *qlist;
        GdmForwardQuery *ret;
        time_t           curtime;
1230

1231 1232
        curtime = time (NULL);
        ret = NULL;
1233

1234
        qlist = g_slist_copy (factory->priv->forward_queries);
1235

1236 1237 1238 1239
        for (li = qlist; li != NULL; li = li->next) {
                GdmForwardQuery *q;
                char            *host;
                char            *serv;
1240

1241
                q = (GdmForwardQuery *) li->data;
1242

1243 1244 1245
                if (q == NULL) {
                        continue;
                }
1246

1247 1248 1249
                host = NULL;
                serv = NULL;
                gdm_address_get_numeric_info (q->dsp_address, &host, &serv);
1250

1251 1252 1253 1254 1255 1256 1257
                g_debug ("gdm_forward_query_lookup: comparing %s:%s", host, serv);
                if (gdm_address_equal (q->dsp_address, address)) {
                        ret = q;
                        g_free (host);
                        g_free (serv);
                        break;
                }
1258

1259 1260 1261
                if (q->acctime > 0 &&  curtime > q->acctime + GDM_FORWARD_QUERY_TIMEOUT) {
                        g_debug ("gdm_forward_query_lookup: Disposing stale forward query from %s:%s",
                                 host, serv);
1262

1263 1264
                        gdm_forward_query_dispose (factory, q);
                }
1265

1266 1267 1268
                g_free (host);
                g_free (serv);
        }
1269

1270
        g_slist_free (qlist);
1271

1272 1273
        if (ret == NULL) {
                char *host;
1274

1275 1276 1277 1278 1279 1280
                host = NULL;
                gdm_address_get_numeric_info (address, &host, NULL);
                g_debug ("gdm_forward_query_lookup: Host %s not found",
                         host);
                g_free (host);
        }
1281

1282
        return ret;
1283 1284 1285
}

static gboolean
1286
create_address_from_request (ARRAY8      *req_addr,
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                             ARRAY8      *req_port,
                             int          family,
                             GdmAddress **address)
{
        uint16_t         port;
        char             host_buf [NI_MAXHOST];
        char             serv_buf [NI_MAXSERV];
        char            *serv;
        const char      *host;
        struct addrinfo  hints;
        struct addrinfo *ai_list;
        struct addrinfo *ai;
        int              gaierr;
        gboolean         found;

        if (address != NULL) {
                *address = NULL;
        }

        if (req_addr == NULL) {
                return FALSE;
        }

        serv = NULL;
        if (req_port != NULL) {
                /* port must always be length 2 */
                if (req_port->length != 2) {
                        return FALSE;
                }

                memcpy (&port, req_port->data, 2);
                snprintf (serv_buf, sizeof (serv_buf), "%d", ntohs (port));
                serv = serv_buf;
        } else {
                /* assume XDM_UDP_PORT */
                snprintf (serv_buf, sizeof (serv_buf), "%d", XDM_UDP_PORT);
                serv = serv_buf;
        }

        host = NULL;
        if (req_addr->length == 4) {
                host = inet_ntop (AF_INET,
                                  (const void *)req_addr->data,
                                  host_buf,
                                  sizeof (host_buf));
        } else if (req_addr->length == 16) {
                host = inet_ntop (AF_INET6,
                                  (const void *)req_addr->data,
                                  host_buf,
                                  sizeof (host_buf));
        }

        if (host == NULL) {
                g_warning (_("Bad address"));
                return FALSE;
        }

        memset (&hints, 0, sizeof (hints));
        hints.ai_family = family;
        hints.ai_flags = AI_V4MAPPED; /* this should convert IPv4 address to IPv6 if needed */
        if ((gaierr = getaddrinfo (host, serv, &hints, &ai_list)) != 0) {
                g_warning ("Unable get address: %s", gai_strerror (gaierr));
                return FALSE;
        }

        /* just take the first one */
        ai = ai_list;

        found = FALSE;
        if (ai != NULL) {
                found = TRUE;
                if (address != NULL) {
                        *address = gdm_address_new_from_sockaddr_storage ((struct sockaddr_storage *)ai->ai_addr);
                }
        }

        freeaddrinfo (ai_list);

        return found;
1366 1367 1368
}

static void
1369
gdm_xdmcp_whack_queued_managed_forwards (GdmXdmcpDisplayFactory *factory,
1370 1371
                                         GdmAddress      *address,
                                         GdmAddress      *origin)
1372
{
1373
        GSList *li;
1374

1375 1376
        for (li = factory->priv->managed_forwards; li != NULL; li = li->next) {
                ManagedForward *mf = li->data;
1377

1378 1379 1380 1381 1382 1383 1384 1385 1386
                if (gdm_address_equal (mf->manager, address) &&
                    gdm_address_equal (mf->origin, origin)) {
                        factory->priv->managed_forwards = g_slist_remove_link (factory->priv->managed_forwards, li);
                        g_slist_free_1 (li);
                        g_source_remove (mf->handler);
                        /* mf freed by glib */
                        return;
                }
        }
1387 1388 1389
}

static void
1390
gdm_xdmcp_handle_forward_query (GdmXdmcpDisplayFactory *factory,
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
                                GdmAddress      *address,
                                int              len)
{
        ARRAY8                   clnt_addr;
        ARRAY8                   clnt_port;
        ARRAYofARRAY8            clnt_authlist;
        int                      i;
        int                      explen;
        GdmAddress              *disp_address;
        char                    *host;
        char                    *serv;

        disp_address = NULL;

        /* Check with tcp_wrappers if client is allowed to access */
        if (! gdm_xdmcp_host_allow (address)) {
                char *host;

                host = NULL;
                gdm_address_get_numeric_info (address, &host, NULL);

                g_warning ("%s: Got FORWARD_QUERY from banned host %s",
                           "gdm_xdmcp_handle_forward query",
                           host);
                g_free (host);
                return;
        }

        /* Read display address */
        if G_UNLIKELY (! XdmcpReadARRAY8 (&factory->priv->buf, &clnt_addr)) {
                g_warning (_("%s: Could not read display address"),
                           "gdm_xdmcp_handle_forward_query");
                return;
        }

        /* Read display port */
        if G_UNLIKELY (! XdmcpReadARRAY8 (&factory->priv->buf, &clnt_port)) {
                XdmcpDisposeARRAY8 (&clnt_addr);
                g_warning (_("%s: Could not read display port number"),
                           "gdm_xdmcp_handle_forward_query");
                return;
        }

        /* Extract array of authentication names from Xdmcp packet */
        if G_UNLIKELY (! XdmcpReadARRAYofARRAY8 (&factory->priv->buf, &clnt_authlist)) {
                XdmcpDisposeARRAY8 (&clnt_addr);
                XdmcpDisposeARRAY8 (&clnt_port);
                g_warning (_("%s: Could not extract authlist from packet"),
                           "gdm_xdmcp_handle_forward_query");
                return;
        }

        /* Crude checksumming */
        explen = 1;
        explen += 2 + clnt_addr.length;
        explen += 2 + clnt_port.length;

        for (i = 0 ; i < clnt_authlist.length ; i++) {
                char *s = g_strndup ((char *) clnt_authlist.data[i].data,
                                     clnt_authlist.length);
                g_debug ("gdm_xdmcp_handle_forward_query: authlist: %s", s);
                g_free (s);

                explen += 2 + clnt_authlist.data[i].length;
        }

        if G_UNLIKELY (len != explen) {
                g_warning (_("%s: Error in checksum"),
                           "gdm_xdmcp_handle_forward_query");
                goto out;
        }

        if (! create_address_from_request (&clnt_addr, &clnt_port, gdm_address_get_family_type (address), &disp_address)) {
                g_warning ("Unable to parse address for request");
                goto out;
        }

        gdm_xdmcp_whack_queued_managed_forwards (factory,
                                                 address,
                                                 disp_address);

        host = NULL;
        serv = NULL;
        gdm_address_get_numeric_info (disp_address, &host, &serv);
        g_debug ("gdm_xdmcp_handle_forward_query: Got FORWARD_QUERY for display: %s, port %s",
                 host, serv);
        g_free (host);
        g_free (serv);

        /* Check with tcp_wrappers if display is allowed to access */
        if (gdm_xdmcp_host_allow (disp_address)) {
                GdmForwardQuery *q;

                q = gdm_forward_query_lookup (factory, disp_address);
                if (q != NULL) {
                        gdm_forward_query_dispose (factory, q);
                }

                gdm_forward_query_alloc (factory, address, disp_address);

                gdm_xdmcp_send_willing (factory, disp_address);
        }
1493 1494 1495

 out:

1496
        gdm_address_free (disp_address);
1497

1498 1499 1500
        XdmcpDisposeARRAYofARRAY8 (&clnt_authlist);
        XdmcpDisposeARRAY8 (&clnt_port);
        XdmcpDisposeARRAY8 (&clnt_addr);
1501 1502 1503
}

static void
1504
gdm_xdmcp_really_send_managed_forward (GdmXdmcpDisplayFactory *factory,
1505 1506
                                       GdmAddress      *address,
                                       GdmAddress      *origin)
1507
{
1508 1509 1510
        ARRAY8      addr;
        XdmcpHeader header;
        char       *host;
1511

1512 1513 1514 1515
        host = NULL;
        gdm_address_get_numeric_info (address, &host, NULL);
        g_debug ("XDMCP: Sending MANAGED_FORWARD to %s", host);
        g_free (host);
1516

1517
        set_address_for_request (origin, &addr);
1518

1519 1520 1521 1522
        header.opcode = (CARD16) GDM_XDMCP_MANAGED_FORWARD;
        header.length = 4 + addr.length;
        header.version = GDM_XDMCP_PROTOCOL_VERSION;
        XdmcpWriteHeader (&factory->priv->buf, &header);
1523

1524 1525 1526 1527 1528
        XdmcpWriteARRAY8 (&factory->priv->buf, &addr);
        XdmcpFlush (factory->priv->socket_fd,
                    &factory->priv->buf,
                    (XdmcpNetaddr)gdm_address_peek_sockaddr_storage (address),
                    (int)sizeof (struct sockaddr_storage));
1529

1530
        g_free (addr.data);
1531 1532 1533 1534 1535
}

static gboolean
managed_forward_handler (ManagedForward *mf)
{
1536 1537 1538 1539 1540
        if (mf->xdmcp_display_factory->priv->socket_fd > 0) {
                gdm_xdmcp_really_send_managed_forward (mf->xdmcp_display_factory,
                                                       mf->manager,
                                                       mf->origin);
        }
1541

1542 1543 1544 1545 1546 1547 1548 1549
        mf->times++;
        if (mf->xdmcp_display_factory->priv->socket_fd <= 0 || mf->times >= 2) {
                mf->xdmcp_display_factory->priv->managed_forwards = g_slist_remove (mf->xdmcp_display_factory->priv->managed_forwards, mf);
                mf->handler = 0;
                /* mf freed by glib */
                return FALSE;
        }
        return TRUE;
1550 1551 1552
}

static void
1553 1554
managed_forward_free (ManagedForward *mf)
{
1555 1556 1557
        gdm_address_free (mf->origin);
        gdm_address_free (mf->manager);
        g_free (mf);
1558 1559 1560
}

static void
1561
gdm_xdmcp_send_managed_forward (GdmXdmcpDisplayFactory *factory,
1562 1563
                                GdmAddress      *address,
                                GdmAddress      *origin)
1564
{
1565
        ManagedForward *mf;
1566

1567
        gdm_xdmcp_really_send_managed_forward (factory, address, origin);
1568

1569 1570 1571
        mf = g_new0 (ManagedForward, 1);
        mf->times = 0;
        mf->xdmcp_display_factory = factory;
1572

1573 1574
        mf->manager = gdm_address_copy (address);
        mf->origin = gdm_address_copy (origin);
1575

1576 1577 1578 1579 1580 1581
        mf->handler = g_timeout_add_full (G_PRIORITY_DEFAULT,
                                          MANAGED_FORWARD_INTERVAL,
                                          (GSourceFunc)managed_forward_handler,
                                          mf,
                                          (GDestroyNotify)managed_forward_free);
        factory->priv->managed_forwards = g_slist_prepend (factory->priv->managed_forwards, mf);
1582 1583 1584
}

static void
1585
gdm_xdmcp_send_got_managed_forward (GdmXdmcpDisplayFactory *factory,
1586 1587
                                    GdmAddress      *address,
                                    GdmAddress      *origin)
1588
{
1589 1590 1591
        ARRAY8      addr;
        XdmcpHeader header;
        char       *host;
1592

1593 1594 1595 1596
        host = NULL;
        gdm_address_get_numeric_info (address, &host, NULL);
        g_debug ("XDMCP: Sending GOT_MANAGED_FORWARD to %s", host);
        g_free (host);
1597

1598
        set_address_for_request (origin, &addr);
1599

1600 1601 1602 1603
        header.opcode = (CARD16) GDM_XDMCP_GOT_MANAGED_FORWARD;
        header.length = 4 + addr.length;
        header.version = GDM_XDMCP_PROTOCOL_VERSION;
        XdmcpWriteHeader (&factory->priv->buf, &header);
1604

1605 1606 1607 1608 1609
        XdmcpWriteARRAY8 (&factory->priv->buf, &addr);
        XdmcpFlush (factory->priv->socket_fd,
                    &factory->priv->buf,
                    (XdmcpNetaddr)gdm_address_peek_sockaddr_storage (address),
                    (int)sizeof (struct sockaddr_storage));
1610 1611
}

1612 1613
static gboolean
count_sessions (const char      *id,
1614 1615
                GdmDisplay      *display,
                GdmXdmcpDisplayFactory *factory)
1616
{
1617 1618
        if (GDM_IS_XDMCP_DISPLAY (display)) {
                int status;
1619

1620
                status = gdm_display_get_status (display);
1621

1622 1623 1624 1625 1626 1627
                if (status == GDM_DISPLAY_MANAGED) {
                        factory->priv->num_sessions++;
                } else if (status == GDM_DISPLAY_UNMANAGED) {
                        factory->priv->num_pending_sessions++;
                }
        }
1628

1629
        return TRUE;
1630 1631 1632
}

static void
1633
gdm_xdmcp_recount_sessions (GdmXdmcpDisplayFactory *factory)
1634
{
1635
        GdmDisplayStore *store;
1636

1637 1638
        factory->priv->num_sessions = 0;
        factory->priv->num_pending_sessions = 0;
1639

1640 1641 1642 1643
        store = gdm_display_factory_get_display_store (GDM_DISPLAY_FACTORY (factory));
        gdm_display_store_foreach (store,
                                   (GdmDisplayStoreFunc)count_sessions,
                                   factory);
1644 1645 1646 1647
}

static gboolean
purge_displays (const char      *id,
1648 1649
                GdmDisplay      *display,
                GdmXdmcpDisplayFactory *factory)
1650
{
1651 1652 1653 1654
        if (GDM_IS_XDMCP_DISPLAY (display)) {
                int status;
                time_t currtime;
                time_t acctime;
1655

1656 1657 1658
                currtime = time (NULL);
                status = gdm_display_get_status (display);
                acctime = gdm_display_get_creation_time (display);
1659