client.c 32 KB
Newer Older
1 2 3 4 5
/* Icecast
 *
 * This program is distributed under the GNU General Public License, version 2.
 * A copy of this license is included with this source.
 *
6
 * Copyright 2000-2004, Jack Moffitt <jack@xiph.org,
7 8 9 10
 *                      Michael Smith <msmith@xiph.org>,
 *                      oddsock <oddsock@xiph.org>,
 *                      Karl Heyes <karl@xiph.org>
 *                      and others (see AUTHORS for details).
11
 * Copyright 2011-2020, Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>,
12 13
 */

Jack Moffitt's avatar
Jack Moffitt committed
14
/* client.c
15 16 17 18
 **
 ** client interface implementation
 **
 */
Jack Moffitt's avatar
Jack Moffitt committed
19

20 21 22 23
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

Jack Moffitt's avatar
Jack Moffitt committed
24 25 26
#include <stdlib.h>
#include <string.h>

27 28
#include <libxml/tree.h>

Marvin Scholz's avatar
Marvin Scholz committed
29 30 31
#include "common/thread/thread.h"
#include "common/avl/avl.h"
#include "common/httpp/httpp.h"
Jack Moffitt's avatar
Jack Moffitt committed
32

33
#include "global.h"
34
#include "refobject.h"
35
#include "cfgfile.h"
Jack Moffitt's avatar
Jack Moffitt committed
36
#include "connection.h"
37
#include "tls.h"
Jack Moffitt's avatar
Jack Moffitt committed
38
#include "refbuf.h"
Karl Heyes's avatar
Karl Heyes committed
39
#include "format.h"
40
#include "stats.h"
41
#include "fserve.h"
42
#include "errors.h"
43 44 45
#include "reportxml.h"
#include "refobject.h"
#include "xslt.h"
46
#include "source.h"
Jack Moffitt's avatar
Jack Moffitt committed
47 48

#include "client.h"
Philipp Schafft's avatar
Philipp Schafft committed
49
#include "auth.h"
Jack Moffitt's avatar
Jack Moffitt committed
50
#include "logging.h"
51

52
#include "util.h"
53
#include "acl.h"
54
#include "listensocket.h"
55
#include "fastevent.h"
56

57
/* for ADMIN_COMMAND_ERROR, and ADMIN_ICESTATS_LEGACY_EXTENSION_APPLICATION */
Philipp Schafft's avatar
Philipp Schafft committed
58 59
#include "admin.h"

60 61 62
#ifdef _WIN32
#define snprintf _snprintf
#endif
Jack Moffitt's avatar
Jack Moffitt committed
63

64 65 66
#undef CATMODULE
#define CATMODULE "client"

67 68
static inline void client_send_500(client_t *client, const char *message);

69 70 71 72 73
/* create a client_t with the provided connection and parser details. Return
 * 0 on success, -1 if server limit has been reached.  In either case a
 * client_t is returned just in case a message needs to be returned. Should
 * be called with global lock held.
 */
74
int client_create(client_t **c_ptr, connection_t *con, http_parser_t *parser)
Jack Moffitt's avatar
Jack Moffitt committed
75
{
Marvin Scholz's avatar
Marvin Scholz committed
76 77
    ice_config_t    *config;
    client_t        *client = (client_t *) calloc(1, sizeof(client_t));
78
    const listener_t *listener_real, *listener_effective;
Marvin Scholz's avatar
Marvin Scholz committed
79
    int              ret    = -1;
80 81

    if (client == NULL)
82
        abort();
83

84
    config = config_get_config();
85 86

    global.clients++;
Marvin Scholz's avatar
Marvin Scholz committed
87
    if (config->client_limit < global.clients) {
88
        ICECAST_LOG_WARN("server client limit reached (%d/%d)", config->client_limit, global.clients);
Marvin Scholz's avatar
Marvin Scholz committed
89
    } else {
90
        ret = 0;
Marvin Scholz's avatar
Marvin Scholz committed
91
    }
Jack Moffitt's avatar
Jack Moffitt committed
92

93 94 95
    config_release_config ();

    stats_event_args (NULL, "clients", "%d", global.clients);
96 97
    client->con = con;
    client->parser = parser;
Philipp Schafft's avatar
Philipp Schafft committed
98
    client->protocol = ICECAST_PROTOCOL_HTTP;
99 100
    client->request_body_length = 0;
    client->request_body_read = 0;
Philipp Schafft's avatar
Philipp Schafft committed
101
    client->admin_command = ADMIN_COMMAND_ERROR;
102 103
    client->refbuf = refbuf_new (PER_CLIENT_REFBUF_SIZE);
    client->refbuf->len = 0; /* force reader code to ignore buffer contents */
104
    client->pos = 0;
105
    client->write_to_client = format_generic_write_to_client;
106
    *c_ptr = client;
Jack Moffitt's avatar
Jack Moffitt committed
107

108 109
    listener_real = listensocket_get_listener(con->listensocket_real);
    listener_effective = listensocket_get_listener(con->listensocket_effective);
110 111
    ICECAST_LOG_DEBUG("Client %p created on connection %p (connection ID: %llu, socket real: %p \"%H\", socket effective: %p \"%H\")",
            client, con, (long long unsigned int)con->id,
112 113
            con->listensocket_real, con->listensocket_real ? listener_real->id : NULL,
            con->listensocket_effective, con->listensocket_effective ? listener_effective->id : NULL
114
            );
115 116
    listensocket_release_listener(con->listensocket_effective);
    listensocket_release_listener(con->listensocket_real);
117

118 119
    fastevent_emit(FASTEVENT_TYPE_CLIENT_CREATE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

120
    return ret;
Jack Moffitt's avatar
Jack Moffitt committed
121 122
}

123 124 125 126 127
void client_complete(client_t *client)
{
    const char *header;
    long long unsigned int scannumber;

128
    do {
129 130 131 132
        header = httpp_getvar(client->parser, "content-length");
        if (header) {
            if (sscanf(header, "%llu", &scannumber) == 1) {
                client->request_body_length = scannumber;
133
                break;
134 135 136
            }
        }

137 138
        if (client->parser->req_type == httpp_req_source) {
            client->request_body_length = -1; /* streaming */
139
            break;
140 141 142 143 144 145
        }

        header = httpp_getvar(client->parser, "transfer-encoding");
        if (header) {
            if (strcasecmp(header, "identity") != 0) {
                client->request_body_length = -1; /* streaming */
146
                break;
147 148 149 150 151 152
            }
        }

        if (client->parser->req_type == httpp_req_put) {
            /* As we don't know yet, we asume this PUT is in streaming mode */
            client->request_body_length = -1; /* streaming */
153
            break;
154 155
        }

156 157 158
        if (client->parser->req_type == httpp_req_none) {
            /* We are a client. If the server did not tell us, we asume streaming. */
            client->request_body_length = -1; /* streaming */
159
            break;
160
        }
161
    } while (0);
162

163 164 165
    ICECAST_LOG_DEBUG("Client %p has request_body_length=%zi", client, client->request_body_length);
}

166 167 168 169 170 171 172 173 174
static inline void client_reuseconnection(client_t *client) {
    connection_t *con;
    reuse_t reuse;

    if (!client)
        return;

    con = client->con;
    reuse = client->reuse;
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

    if (reuse == ICECAST_REUSE_UPGRADETLS) {
        http_parser_t *parser = client->parser;

        httpp_deletevar(parser, "upgrade");
        client->reuse = ICECAST_REUSE_CLOSE;

        /* release the buffer now, as the buffer could be on the source queue
         * and may of disappeared after auth completes */
        client_set_queue(client, NULL);
        client->refbuf = refbuf_new (PER_CLIENT_REFBUF_SIZE);
        client->refbuf->len = 0; /* force reader code to ignore buffer contents */
        client->pos = 0;

        connection_uses_tls(con);
        connection_queue_client(client);

        return;
    }

    con = connection_create(con->sock, con->listensocket_real, con->listensocket_effective, strdup(con->ip));
196
    client->con->sock = -1; /* TODO: do not use magic */
197 198

    /* handle to keep the TLS connection */
199
    if (client->con->tls) {
200
        /* AHhhggrr.. That pain....
201
         * stealing TLS state...
202
         */
203
        con->tls  = client->con->tls;
204 205
        con->read = client->con->read;
        con->send = client->con->send;
206
        client->con->tls  = NULL;
207 208 209 210
        client->con->read = NULL;
        client->con->send = NULL;
    }

211 212 213 214 215 216 217 218 219 220
    if (client->con->readbufferlen) {
        /* Aend... moorre paaiin.
         * stealing putback buffer.
         */
        con->readbuffer = client->con->readbuffer;
        con->readbufferlen = client->con->readbufferlen;
        client->con->readbuffer = NULL;
        client->con->readbufferlen = 0;
    }

221 222 223 224 225 226
    client->reuse = ICECAST_REUSE_CLOSE;

    client_destroy(client);
    connection_queue(con);
}

Jack Moffitt's avatar
Jack Moffitt committed
227 228
void client_destroy(client_t *client)
{
Philipp Schafft's avatar
Philipp Schafft committed
229
    ICECAST_LOG_DEBUG("Called to destory client %p", client);
Karl Heyes's avatar
Karl Heyes committed
230 231
    if (client == NULL)
        return;
232

233 234
    fastevent_emit(FASTEVENT_TYPE_CLIENT_DESTROY, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

235
    if (client->reuse != ICECAST_REUSE_CLOSE) {
236 237 238 239 240
        /* only reuse the client if we reached the body's EOF. */
        if (client_body_eof(client) == 1) {
            client_reuseconnection(client);
            return;
        }
241 242
    }

243 244
    /* release the buffer now, as the buffer could be on the source queue
     * and may of disappeared after auth completes */
245
    client_set_queue(client, NULL);
246

Philipp Schafft's avatar
Philipp Schafft committed
247
    if (auth_release_client(client))
248 249
        return;

250
    /* write log entry if ip is set (some things don't set it, like outgoing
251 252
     * slave requests
     */
Karl Heyes's avatar
Karl Heyes committed
253
    if (client->respcode && client->parser)
254
        logging_access(client);
255 256
    if (client->con)
        connection_close(client->con);
Karl Heyes's avatar
Karl Heyes committed
257 258
    if (client->parser)
        httpp_destroy(client->parser);
259 260
    if (client->encoding)
        httpp_encoding_release(client->encoding);
Jack Moffitt's avatar
Jack Moffitt committed
261

262
    global_lock();
263
    global.clients--;
264 265
    stats_event_args(NULL, "clients", "%d", global.clients);
    global_unlock();
266

267 268
    /* we need to free client specific format data (if any) */
    if (client->free_client_data)
269
        client->free_client_data(client);
270

271 272
    refobject_unref(client->handler_module);
    free(client->handler_function);
273
    free(client->uri);
Michael Smith's avatar
Michael Smith committed
274
    free(client->username);
Karl Heyes's avatar
Karl Heyes committed
275
    free(client->password);
Philipp Schafft's avatar
Philipp Schafft committed
276 277
    free(client->role);
    acl_release(client->acl);
Michael Smith's avatar
Michael Smith committed
278

279
    free(client);
Jack Moffitt's avatar
Jack Moffitt committed
280
}
281

282
/* helper function for reading data from a client */
283 284 285 286 287 288 289 290 291 292 293 294 295 296
static ssize_t __client_read_bytes_real(client_t *client, void *buf, size_t len)
{
    /* we have data to read from a refbuf first */
    if (client->refbuf->len < len)
        len = client->refbuf->len;
    memcpy (buf, client->refbuf->data, len);
    if (len < client->refbuf->len) {
        char *ptr = client->refbuf->data;
        memmove (ptr, ptr+len, client->refbuf->len - len);
    }
    client->refbuf->len -= len;
    return len;
}

297
int client_read_bytes(client_t *client, void *buf, unsigned len)
298
{
299 300
    ssize_t (*reader)(void*, void*, size_t) = (ssize_t(*)(void*,void*,size_t))__client_read_bytes_real;
    void *userdata = client;
301
    int bytes;
302

303 304 305 306 307 308 309 310 311
    if (!(client->refbuf && client->refbuf->len)) {
        reader = (ssize_t(*)(void*,void*,size_t))connection_read_bytes;
        userdata = client->con;
    }

    if (client->encoding) {
        bytes = httpp_encoding_read(client->encoding, buf, len, reader, userdata);
    } else {
        bytes = reader(userdata, buf, len);
312
    }
313

314
    if (bytes == -1 && client->con->error)
315
        ICECAST_LOG_DEBUG("reading from connection has failed");
316

317 318
    fastevent_emit(FASTEVENT_TYPE_CLIENT_READ, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_OBRD, client, buf, (size_t)len, (ssize_t)bytes);

319
    return bytes;
320 321
}

322
static inline void _client_send_report(client_t *client, const char *uuid, const char *message, int http_status, const char *location)
323
{
324 325 326 327 328 329 330 331 332 333
    reportxml_t *report;
    admin_format_t admin_format;
    const char *xslt = NULL;

    admin_format = client_get_admin_format_by_content_negotiation(client);

    switch (admin_format) {
        case ADMIN_FORMAT_RAW:
            xslt = NULL;
        break;
334 335
        case ADMIN_FORMAT_HTML:
            xslt = CLIENT_DEFAULT_ERROR_XSL_HTML;
336 337 338 339 340 341 342
        break;
        case ADMIN_FORMAT_PLAINTEXT:
            xslt = CLIENT_DEFAULT_ERROR_XSL_PLAINTEXT;
        break;
        default:
            client_send_500(client, "Invalid Admin Type");
        break;
343 344
    }

345
    report = client_get_reportxml(uuid, NULL, message);
346

347
    client_send_reportxml(client, report, DOCUMENT_DOMAIN_ADMIN, xslt, admin_format, http_status, location);
348

349
    refobject_unref(report);
350 351
}

352
void client_send_error_by_error(client_t *client, const icecast_error_t *error)
353 354 355 356 357 358 359
{

    if (!error) {
         client_send_500(client, "Unknown error ID");
         return;
    }

360 361 362
    if (error->http_status == 500) {
         client_send_500(client, error->message);
        return;
363 364
    }

365 366 367 368 369 370 371 372 373
    _client_send_report(client, error->uuid, error->message, error->http_status, NULL);
}
void client_send_error_by_uuid(client_t *client, const char *uuid)
{
    client_send_error_by_error(client, error_get_by_uuid(uuid));
}
void client_send_error_by_id(client_t *client, icecast_error_id_t id)
{
    client_send_error_by_error(client, error_get_by_id(id));
374 375
}

376 377 378 379 380 381 382 383 384 385 386 387
void client_send_101(client_t *client, reuse_t reuse)
{
    ssize_t ret;

    if (!client)
        return;

    if (reuse != ICECAST_REUSE_UPGRADETLS) {
        client_send_500(client, "Bad reuse parameter");
        return;
    }

388 389
    client->reuse = reuse;

390 391 392 393 394 395
    ret = util_http_build_header(client->refbuf->data, PER_CLIENT_REFBUF_SIZE, 0,
                                 0, 101, NULL,
                                 "text/plain", "utf-8",
                                 NULL, NULL, client);

    snprintf(client->refbuf->data + ret, PER_CLIENT_REFBUF_SIZE - ret,
396
             "Content-Length: 0\r\nUpgrade: TLS/1.0, HTTP/1.1\r\n\r\n");
397 398 399 400

    client->respcode = 101;
    client->refbuf->len = strlen(client->refbuf->data);

401 402
    fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

403 404 405
    fserve_add_client(client, NULL);
}

406 407
void client_send_204(client_t *client)
{
408
    source_t *source;
409 410 411 412 413 414 415
    ssize_t ret;

    if (!client)
        return;

    client->reuse = ICECAST_REUSE_KEEPALIVE;

416 417 418 419 420
    /* We get a source_t* here as this is likely a reply to OPTIONS and we want
     * to have as much infos as possible in that case.
     */
    avl_tree_rlock(global.source_tree);
    source = source_find_mount_raw(client->uri);
421 422 423
    ret = util_http_build_header(client->refbuf->data, PER_CLIENT_REFBUF_SIZE, 0,
                                 0, 204, NULL,
                                 NULL, NULL,
424 425
                                 NULL, source, client);
    avl_tree_unlock(global.source_tree);
426 427 428 429 430 431 432

    snprintf(client->refbuf->data + ret, PER_CLIENT_REFBUF_SIZE - ret,
             "Content-Length: 0\r\n\r\n");

    client->respcode = 204;
    client->refbuf->len = strlen(client->refbuf->data);

433 434
    fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

435 436 437
    fserve_add_client(client, NULL);
}

438 439 440 441 442 443 444 445 446 447 448 449
void client_send_426(client_t *client, reuse_t reuse)
{
    ssize_t ret;

    if (!client)
        return;

    if (reuse != ICECAST_REUSE_UPGRADETLS) {
        client_send_500(client, "Bad reuse parameter");
        return;
    }

450 451
    client->reuse = reuse;

452 453 454 455 456 457
    ret = util_http_build_header(client->refbuf->data, PER_CLIENT_REFBUF_SIZE, 0,
                                 0, 426, NULL,
                                 "text/plain", "utf-8",
                                 NULL, NULL, client);

    snprintf(client->refbuf->data + ret, PER_CLIENT_REFBUF_SIZE - ret,
458
             "Content-Length: 0\r\nUpgrade: TLS/1.0, HTTP/1.1\r\n\r\n");
459 460 461 462 463 464

    client->respcode = 426;
    client->refbuf->len = strlen(client->refbuf->data);

    client->reuse = ICECAST_REUSE_KEEPALIVE;

465 466
    fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

467 468 469
    fserve_add_client(client, NULL);
}

470
/* this function is designed to work even if client is in bad state */
Marvin Scholz's avatar
Marvin Scholz committed
471 472
static inline void client_send_500(client_t *client, const char *message)
{
473 474
    const char header[] = "HTTP/1.0 500 Internal Server Error\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n"
                          "500 - Internal Server Error\n---------------------------\n";
475 476
    const ssize_t header_len = sizeof(header) - 1;
    ssize_t ret;
477

478 479 480 481
    client->respcode = 500;
    client->refbuf->len = 0;
    fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);

482 483 484 485 486 487 488 489
    ret = client_send_bytes(client, header, header_len);

    /* only send message if we have one AND if header could have transmitted completly */
    if (message && ret == header_len)
        client_send_bytes(client, message, strlen(message));

    client_destroy(client);
}
490

491 492 493 494 495
void client_send_redirect(client_t *client, const char *uuid, int status, const char *location)
{
    _client_send_report(client, uuid, "Redirecting", status, location);
}

496
/* this function sends a reportxml file to the client in the prefered format. */
497
void client_send_reportxml(client_t *client, reportxml_t *report, document_domain_t domain, const char *xsl, admin_format_t admin_format_hint, int status, const char *location)
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
{
    admin_format_t admin_format;
    xmlDocPtr doc;

    if (!client)
        return;

    if (!report) {
        ICECAST_LOG_ERROR("No report xml given. Sending 500 to client %p", client);
        client_send_500(client, "No report.");
        return;
    }

    if (!status)
        status = 200;

    if (admin_format_hint == ADMIN_FORMAT_AUTO) {
        admin_format = client_get_admin_format_by_content_negotiation(client);
    } else {
        admin_format = admin_format_hint;
    }

    if (!xsl) {
        switch (admin_format) {
            case ADMIN_FORMAT_RAW:
                /* noop, we don't need to set xsl */
            break;
525 526
            case ADMIN_FORMAT_HTML:
                xsl = CLIENT_DEFAULT_REPORT_XSL_HTML;
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
            break;
            case ADMIN_FORMAT_PLAINTEXT:
                xsl = CLIENT_DEFAULT_REPORT_XSL_PLAINTEXT;
            break;
            default:
                ICECAST_LOG_ERROR("Unsupported admin format and no XSLT file given. Sending 500 to client %p", client);
                client_send_500(client, "Unsupported admin format.");
                return;
            break;
        }
    } else if (admin_format_hint == ADMIN_FORMAT_AUTO) {
        ICECAST_LOG_ERROR("No explicit admin format but XSLT file given. BUG. Sending 500 to client %p", client);
        client_send_500(client, "Admin type AUTO but XSLT.");
        return;
    }

    doc = reportxml_render_xmldoc(report);
    if (!doc) {
        ICECAST_LOG_ERROR("Can not render XML Document from report. Sending 500 to client %p", client);
        client_send_500(client, "Can not render XML Document from report.");
        return;
    }

    if (admin_format == ADMIN_FORMAT_RAW) {
        xmlChar *buff = NULL;
552
        size_t location_length = 0;
553 554 555 556 557 558
        int len = 0;
        size_t buf_len;
        ssize_t ret;

        xmlDocDumpMemory(doc, &buff, &len);

559 560 561 562 563
        if (location) {
            location_length = strlen(location);
        }

        buf_len = len + location_length + 1024;
564 565 566 567 568
        if (buf_len < 4096)
            buf_len = 4096;

        client_set_queue(client, NULL);
        client->refbuf = refbuf_new(buf_len);
569
        client->reuse = ICECAST_REUSE_KEEPALIVE;
570 571 572 573 574 575 576 577 578 579

        ret = util_http_build_header(client->refbuf->data, buf_len, 0,
                0, status, NULL,
                "text/xml", "utf-8",
                NULL, NULL, client);
        if (ret < 0) {
            ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
            client_send_error_by_id(client, ICECAST_ERROR_GEN_HEADER_GEN_FAILED);
            xmlFree(buff);
            return;
580
        } else if (buf_len < (size_t)(len + location_length + ret + 128)) {
581
            void *new_data;
582
            buf_len = ret + len + 128;
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
            new_data = realloc(client->refbuf->data, buf_len);
            if (new_data) {
                ICECAST_LOG_DEBUG("Client buffer reallocation succeeded.");
                client->refbuf->data = new_data;
                client->refbuf->len = buf_len;
                ret = util_http_build_header(client->refbuf->data, buf_len, 0,
                        0, status, NULL,
                        "text/xml", "utf-8",
                        NULL, NULL, client);
                if (ret == -1) {
                    ICECAST_LOG_ERROR("Dropping client as we can not build response headers.");
                    client_send_error_by_id(client, ICECAST_ERROR_GEN_HEADER_GEN_FAILED);
                    xmlFree(buff);
                    return;
                }
            } else {
                ICECAST_LOG_ERROR("Client buffer reallocation failed. Dropping client.");
                client_send_error_by_id(client, ICECAST_ERROR_GEN_BUFFER_REALLOC);
                xmlFree(buff);
                return;
            }
        }

        /* FIXME: in this section we hope no function will ever return -1 */
607 608 609 610
        if (location) {
            ret += snprintf(client->refbuf->data + ret, buf_len - ret, "Location: %s\r\n", location);
        }
        ret += snprintf(client->refbuf->data + ret, buf_len - ret, "Content-Length: %d\r\n\r\n%s", xmlStrlen(buff), buff);
611 612 613 614

        client->refbuf->len = ret;
        xmlFree(buff);
        client->respcode = status;
615
        fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
        fserve_add_client (client, NULL);
    } else {
        char *fullpath_xslt_template;
        const char *document_domain_path;
        ssize_t fullpath_xslt_template_len;
        ice_config_t *config;

        config = config_get_config();
        switch (domain) {
            case DOCUMENT_DOMAIN_WEB:
                document_domain_path = config->webroot_dir;
            break;
            case DOCUMENT_DOMAIN_ADMIN:
                document_domain_path = config->adminroot_dir;
            break;
            default:
                config_release_config();
                ICECAST_LOG_ERROR("Invalid document domain. Sending 500 to client %p", client);
                client_send_500(client, "Invalid document domain.");
                return;
            break;
        }
        fullpath_xslt_template_len = strlen(document_domain_path) + strlen(xsl) + strlen(PATH_SEPARATOR) + 1;
        fullpath_xslt_template = malloc(fullpath_xslt_template_len);
        snprintf(fullpath_xslt_template, fullpath_xslt_template_len, "%s%s%s", document_domain_path, PATH_SEPARATOR, xsl);
        config_release_config();

        ICECAST_LOG_DEBUG("Sending XSLT (%s)", fullpath_xslt_template);
644
        fastevent_emit(FASTEVENT_TYPE_CLIENT_SEND_RESPONSE, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_CLIENT, client);
645
        xslt_transform(doc, fullpath_xslt_template, client, status, location);
646 647 648 649 650 651
        free(fullpath_xslt_template);
    }

    xmlFreeDoc(doc);
}

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
static void client_get_reportxml__add_basic_stats(reportxml_t *report)
{
    reportxml_node_t *rootnode, *extension;
    xmlNodePtr xmlroot;
    xmlNodePtr modules;

    rootnode = reportxml_get_root_node(report);

    extension = reportxml_node_new(REPORTXML_NODE_TYPE_EXTENSION, NULL, NULL, NULL);
    reportxml_node_set_attribute(extension, "application", ADMIN_ICESTATS_LEGACY_EXTENSION_APPLICATION);

    reportxml_node_add_child(rootnode, extension);

    refobject_unref(rootnode);

    xmlroot = xmlNewNode(NULL, XMLSTR("icestats"));
    modules = module_container_get_modulelist_as_xml(global.modulecontainer);
    xmlAddChild(xmlroot, modules);


    reportxml_node_add_xml_child(extension, xmlroot);
    refobject_unref(extension);
    xmlFreeNode(xmlroot);
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
reportxml_t *client_get_reportxml(const char *state_definition, const char *state_akindof, const char *state_text)
{
    reportxml_t *report = NULL;

    if (state_definition) {
        ice_config_t *config;

        config = config_get_config();
        report = reportxml_database_build_report(config->reportxml_db, state_definition, -1);
        config_release_config();
    }

    if (!report) {
        reportxml_node_t *rootnode, *incidentnode, *statenode;

692
        report = refobject_new(reportxml_t);
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
        rootnode = reportxml_get_root_node(report);
        incidentnode = reportxml_node_new(REPORTXML_NODE_TYPE_INCIDENT, NULL, NULL, NULL);
        statenode = reportxml_node_new(REPORTXML_NODE_TYPE_STATE, NULL, state_definition, state_akindof);

        if (state_text) {
            reportxml_node_t *textnode;

            textnode = reportxml_node_new(REPORTXML_NODE_TYPE_TEXT, NULL, NULL, NULL);
            reportxml_node_set_content(textnode, state_text);
            reportxml_node_add_child(statenode, textnode);
            refobject_unref(textnode);
        }

        reportxml_node_add_child(incidentnode, statenode);
        reportxml_node_add_child(rootnode, incidentnode);
        refobject_unref(statenode);
        refobject_unref(incidentnode);
        refobject_unref(rootnode);
    }

713 714
    client_get_reportxml__add_basic_stats(report);

715 716 717
    return report;
}

718 719 720 721 722 723 724 725 726 727 728 729
admin_format_t client_get_admin_format_by_content_negotiation(client_t *client)
{
    const char *pref;

    if (!client || !client->parser)
        return CLIENT_DEFAULT_ADMIN_FORMAT;

    pref = util_http_select_best(httpp_getvar(client->parser, "accept"), "text/xml", "text/html", "text/plain", (const char*)NULL);

    if (strcmp(pref, "text/xml") == 0) {
        return ADMIN_FORMAT_RAW;
    } else if (strcmp(pref, "text/html") == 0) {
730
        return ADMIN_FORMAT_HTML;
731 732 733 734 735 736 737
    } else if (strcmp(pref, "text/plain") == 0) {
        return ADMIN_FORMAT_PLAINTEXT;
    } else {
        return CLIENT_DEFAULT_ADMIN_FORMAT;
    }
}

738
/* helper function for sending the data to a client */
739
int client_send_bytes(client_t *client, const void *buf, unsigned len)
740
{
741
    int ret = connection_send_bytes(client->con, buf, len);
742 743

    if (client->con->error)
744
        ICECAST_LOG_DEBUG("Client connection died");
745

746 747
    fastevent_emit(FASTEVENT_TYPE_CLIENT_WRITE, FASTEVENT_FLAG_NONE, FASTEVENT_DATATYPE_OBRD, client, buf, (size_t)len, (ssize_t)ret);

748 749 750
    return ret;
}

751
void client_set_queue(client_t *client, refbuf_t *refbuf)
Karl Heyes's avatar
Karl Heyes committed
752 753 754 755
{
    refbuf_t *to_release = client->refbuf;

    client->refbuf = refbuf;
Karl Heyes's avatar
Karl Heyes committed
756
    if (refbuf)
757
        refbuf_addref(client->refbuf);
Karl Heyes's avatar
Karl Heyes committed
758 759
    client->pos = 0;
    if (to_release)
760
        refbuf_release(to_release);
Karl Heyes's avatar
Karl Heyes committed
761
}
762 763 764

ssize_t client_body_read(client_t *client, void *buf, size_t len)
{
765 766
    ssize_t ret;

767
    ICECAST_LOG_DDEBUG("Reading from body (client=%p)", client);
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

    if (client->request_body_length != -1) {
        size_t left = (size_t)client->request_body_length - client->request_body_read;
        if (len > left) {
            ICECAST_LOG_DEBUG("Limiting read request to left over body size: left %zu byte, requested %zu byte", left, len);
            len = left;
        }
    }

    ret = client_read_bytes(client, buf, len);

    if (ret > 0) {
        client->request_body_read += ret;
    }

783 784
    fastevent_emit(FASTEVENT_TYPE_CLIENT_READ_BODY, FASTEVENT_FLAG_MODIFICATION_ALLOWED, FASTEVENT_DATATYPE_OBRD, client, buf, len, ret);

785
    return ret;
786 787
}

788 789
/* we might un-static this if needed at some time in distant future. -- ph3-der-loewe, 2018-04-17 */
static int client_eof(client_t *client)
790
{
791 792 793
    if (!client)
        return -1;

794 795 796
    if (!client->con)
        return 0;

797
    if (client->con->tls && tls_got_shutdown(client->con->tls) > 0)
798 799 800 801 802 803 804
        client->con->error = 1;

    if (client->con->error)
        return 1;

    return 0;
}
805 806 807 808 809 810 811 812

int client_body_eof(client_t *client)
{
    int ret = -1;

    if (!client)
        return -1;

813
    if (client->request_body_length != -1 && client->request_body_read == (size_t)client->request_body_length) {
814
        ICECAST_LOG_DDEBUG("Reached given body length (client=%p)", client);
815 816
        ret = 1;
    } else if (client->encoding) {
817
        ICECAST_LOG_DDEBUG("Looking for body EOF with encoding (client=%p)", client);
818 819
        ret = httpp_encoding_eof(client->encoding, (int(*)(void*))client_eof, client);
    } else {
820
        ICECAST_LOG_DDEBUG("Looking for body EOF without encoding (client=%p)", client);
821 822 823
        ret = client_eof(client);
    }

824
    ICECAST_LOG_DDEBUG("... result is: %i (client=%p)", ret, client);
825 826
    return ret;
}
827 828 829 830 831 832 833 834 835 836 837 838 839

client_slurp_result_t client_body_slurp(client_t *client, void *buf, size_t *len)
{
    if (!client || !buf || !len)
        return CLIENT_SLURP_ERROR;

    if (client->request_body_length != -1) {
        /* non-streaming mode */
        size_t left = (size_t)client->request_body_length - client->request_body_read;

        if (!left)
            return CLIENT_SLURP_SUCCESS;

840
        if (*len < (size_t)client->request_body_length)
841 842 843 844 845 846 847
            return CLIENT_SLURP_BUFFER_TO_SMALL;

        if (left > 2048)
            left = 2048;

        client_body_read(client, buf + client->request_body_read, left);

848
        if ((size_t)client->request_body_length == client->request_body_read) {
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
            *len = client->request_body_read;

            return CLIENT_SLURP_SUCCESS;
        } else {
            return CLIENT_SLURP_NEEDS_MORE_DATA;
        }
    } else {
        /* streaming mode */
        size_t left = *len - client->request_body_read;
        int ret;

        if (left) {
            if (left > 2048)
                left = 2048;

            client_body_read(client, buf + client->request_body_read, left);
        }

        ret = client_body_eof(client);
        switch (ret) {
            case 0:
                if (*len == client->request_body_read) {
                    return CLIENT_SLURP_BUFFER_TO_SMALL;
                }
                return CLIENT_SLURP_NEEDS_MORE_DATA;
            break;
            case 1:
                return CLIENT_SLURP_SUCCESS;
            break;
            default:
                return CLIENT_SLURP_ERROR;
            break;
        }
    }
}

client_slurp_result_t client_body_skip(client_t *client)
{
    char buf[2048];
    int ret;

890
    ICECAST_LOG_DEBUG("Slurping client %p", client);
891 892

    if (!client) {
893
        ICECAST_LOG_DEBUG("Slurping client %p ... failed", client);
894
        return CLIENT_SLURP_ERROR;
895
    }
896 897 898 899

    if (client->request_body_length != -1) {
        size_t left = (size_t)client->request_body_length - client->request_body_read;

900
        if (!left) {
901
            ICECAST_LOG_DEBUG("Slurping client %p ... was a success", client);
902
            return CLIENT_SLURP_SUCCESS;
903
        }
904 905 906 907 908 909

        if (left > sizeof(buf))
            left = sizeof(buf);

        client_body_read(client, buf, left);

910
        if ((size_t)client->request_body_length == client->request_body_read) {
911
            ICECAST_LOG_DEBUG("Slurping client %p ... was a success", client);
912 913
            return CLIENT_SLURP_SUCCESS;
        } else {
914
            ICECAST_LOG_DEBUG("Slurping client %p ... needs more data", client);
915 916 917 918 919 920 921 922 923
            return CLIENT_SLURP_NEEDS_MORE_DATA;
        }
    } else {
        client_body_read(client, buf, sizeof(buf));
    }

    ret = client_body_eof(client);
    switch (ret) {
        case 0:
924
            ICECAST_LOG_DEBUG("Slurping client %p ... needs more data", client);
925 926 927
            return CLIENT_SLURP_NEEDS_MORE_DATA;
        break;
        case 1:
928
            ICECAST_LOG_DEBUG("Slurping client %p ... was a success", client);
929 930 931
            return CLIENT_SLURP_SUCCESS;
        break;
        default:
932
            ICECAST_LOG_DEBUG("Slurping client %p ... failed", client);
933 934 935 936
            return CLIENT_SLURP_ERROR;
        break;
    }
}
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 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

ssize_t client_get_baseurl(client_t *client, listensocket_t *listensocket, char *buf, size_t len, const char *user, const char *pw, const char *prefix, const char *suffix0, const char *suffix1)
{
    const listener_t *listener = NULL;
    const ice_config_t *config = NULL;
    const char *host = NULL;
    const char *proto = "http";
    int port = 0;
    ssize_t ret;
    tlsmode_t tlsmode = ICECAST_TLSMODE_AUTO;
    protocol_t protocol = ICECAST_PROTOCOL_HTTP;

    if (!buf || !len)
        return -1;

    if (!prefix)
        prefix = "";

    if (!suffix0)
        suffix0 = "";

    if (!suffix1)
        suffix1 = "";

    if (client) {
        host = httpp_getvar(client->parser, "host");

        /* at least a couple of players (fb2k/winamp) are reported to send a
         * host header but without the port number. So if we are missing the
         * port then lets treat it as if no host line was sent */
        if (host && strchr(host, ':') == NULL)
            host = NULL;

        listensocket = client->con->listensocket_effective;
        tlsmode = client->con->tlsmode;
        protocol = client->protocol;
    }

    if (!host && listensocket) {
        listener = listensocket_get_listener(listensocket);
        if (listener) {
            host = listener->bind_address;
            port = listener->port;
            if (!client)
                tlsmode = listener->tls;
        }
    }

    if (!host) {
        config = config_get_config();
        host = config->hostname;
        if (!port)
            port = config->port;
    }

    switch (tlsmode) {
        case ICECAST_TLSMODE_DISABLED:
        case ICECAST_TLSMODE_AUTO:
            switch (protocol) {
                case ICECAST_PROTOCOL_HTTP: proto = "http"; break;
                case ICECAST_PROTOCOL_SHOUTCAST: proto = "icy"; break;
            }
            break;
        case ICECAST_TLSMODE_AUTO_NO_PLAIN:
        case ICECAST_TLSMODE_RFC2817:
        case ICECAST_TLSMODE_RFC2818:
            switch (protocol) {
                case ICECAST_PROTOCOL_HTTP: proto = "https"; break;
                case ICECAST_PROTOCOL_SHOUTCAST: proto = "icys"; break;
            }
            break;
    }

    if (host && port) {
        ret = snprintf(buf, len, "%s%s://%s%s%s%s%s:%i%s%s", prefix, proto, user ? user : "", pw ? ":" : "", pw ? pw : "", (user || pw) ? "@" : "", host, port, suffix0, suffix1);
    } else if (host) {
        ret = snprintf(buf, len, "%s%s://%s%s%s%s%s%s%s", prefix, proto, user ? user : "", pw ? ":" : "", pw ? pw : "", (user || pw) ? "@" : "", host, suffix0, suffix1);
    } else {
        ret = -1;
    }

    if (config)
        config_release_config();
    if (listener)
        listensocket_release_listener(listensocket);

    return ret;
}