nth_server.c 31.8 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
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 37 38
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

/**@file nth_server.c
 * @brief HTTP server.
 * 
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * 
 * @date Created: Sat Oct 19 01:37:36 2002 ppessi
 */

#include "config.h"

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
39
#include <errno.h>
Pekka Pessi's avatar
Pekka Pessi committed
40
#include <assert.h>
Pekka Pessi's avatar
Pekka Pessi committed
41

42
#include <sofia-sip/string0.h>
43
#include <sofia-sip/hostdomain.h>
Pekka Pessi's avatar
Pekka Pessi committed
44

45 46 47 48
#if !defined(EALREADY) && defined(_WIN32)
#define EALREADY WSAEALREADY
#endif

Pekka Pessi's avatar
Pekka Pessi committed
49 50 51 52 53
typedef struct server_s server_t;

/** @internal SU timer argument pointer type */
#define SU_TIMER_ARG_T server_t

54 55 56
#include <sofia-sip/http_header.h>
#include <sofia-sip/http_status.h>
#include <sofia-sip/http_tag.h>
Pekka Pessi's avatar
Pekka Pessi committed
57

58
#include "sofia-sip/nth.h"
Pekka Pessi's avatar
Pekka Pessi committed
59

60 61 62
#include <sofia-sip/msg_date.h>
#include <sofia-sip/msg_addr.h>
#include <sofia-sip/su_tagarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
63

64 65
#include <sofia-sip/hostdomain.h>

Pekka Pessi's avatar
Pekka Pessi committed
66 67 68 69
/* We are customer of tport_t */
#define TP_STACK_T   server_t
#define TP_MAGIC_T   void
                                     
70 71
#include <sofia-sip/tport.h>
#include <sofia-sip/htable.h>
Pekka Pessi's avatar
Pekka Pessi committed
72

73 74
#include <sofia-sip/auth_module.h>

75 76 77 78
#ifndef UINT32_MAX
#define UINT32_MAX (0xffffffffU)
#endif

Pekka Pessi's avatar
Pekka Pessi committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
enum { SERVER_TICK = 1000 };

#define SERVER_VERSION "nth/" NTH_VERSION

HTABLE_DECLARE(hc_htable, hct, nth_client_t);

struct server_s 
{
  su_home_t          srv_home[1];
  su_root_t         *srv_root;

  su_timer_t        *srv_timer;
  unsigned           srv_now;

  msg_mclass_t const*srv_mclass;
  int                srv_mflags;	/**< Message flags */

  tport_t           *srv_tports;
  unsigned           srv_queuesize;	/**< Maximum number of queued responses */

  size_t             srv_max_bodylen;	/**< Maximum accepted length */

  unsigned           srv_persistent:1;	/**< Allow persistent connections */

  /** Sites */
  nth_site_t        *srv_sites;

  /* Statistics */
  struct {
    uint32_t           st_requests;     /**< Received requests */
    uint32_t           st_responses;    /**< Sent responses */
    uint32_t           st_bad;		/**< Bad requests */
  }                  srv_stats[1];

  http_server_t     *srv_server;      /**< Server header */
};

struct nth_site_s 
{
118 119
  nth_site_t          *site_next, **site_prev;

Pekka Pessi's avatar
Pekka Pessi committed
120 121 122
  nth_site_t          *site_kids;

  server_t            *site_server;
123
  auth_mod_t          *site_auth;
Pekka Pessi's avatar
Pekka Pessi committed
124 125 126 127 128 129 130 131

  url_t               *site_url;
  char const          *site_path;
  size_t               site_path_len;

  nth_request_f       *site_callback;
  nth_site_magic_t    *site_magic;

132
  /** Host header must match with server name */
Pekka Pessi's avatar
Pekka Pessi committed
133
  unsigned             site_strict : 1;
134 135 136 137
  /** Site can have kids */
  unsigned             site_isdir : 1;
  /** Site does not have domain name */
  unsigned             site_wildcard : 1;
Pekka Pessi's avatar
Pekka Pessi committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
};

struct nth_request_s
{
  server_t              *req_server;

  http_method_t        	req_method;
  char const           *req_method_name;
  url_t const          *req_url;         /**< RequestURI  */
  char const           *req_version;
  
  tport_t              *req_tport;
  msg_t		       *req_request;
  msg_t                *req_response;

153 154
  auth_status_t        *req_as;

Pekka Pessi's avatar
Pekka Pessi committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168
  unsigned short      	req_status;
  unsigned              req_close : 1; /**< Client asked for close */
  unsigned              req_in_callback : 1;
  unsigned              req_destroyed : 1;
};

/* ====================================================================== */
/* Debug log settings */

#define SU_LOG   nth_server_log

#ifdef SU_DEBUG_H
#error <su_debug.h> included directly.
#endif
169
#include <sofia-sip/su_debug.h>
Pekka Pessi's avatar
Pekka Pessi committed
170

Pekka Pessi's avatar
Pekka Pessi committed
171
/**Environment variable determining the debug log level for @b nth
Pekka Pessi's avatar
Pekka Pessi committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
 * module.
 *
 * The NTH_DEBUG environment variable is used to determine the debug
 * logging level for @b nth module. The default level is 1.
 * 
 * @sa <su_debug.h>, nth_server_log, SOFIA_DEBUG
 */
extern char const NTH_DEBUG[];

#ifndef SU_DEBUG
#define SU_DEBUG 1
#endif

/**Debug log for @b nth module. 
 * 
 * The nth_server_log is the log object used by @b nth module. The level of
 * #nth_server_log is set using #NTH_DEBUG environment variable.
 */
su_log_t nth_server_log[] = { SU_LOG_INIT("nth", "NTH_DEBUG", SU_DEBUG) };

#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "nth";
#endif

/* ====================================================================== */
/** Server side
 */
static server_t *server_create(url_t const *url,
			       tag_type_t tag, tag_value_t value, ...);
void server_destroy(server_t *srv);
static inline int server_timer_init(server_t *srv);
static void server_timer(su_root_magic_t *rm, su_timer_t *timer, server_t *srv);
static inline uint32_t server_now(server_t const *srv);
static void server_request(server_t *srv, tport_t *tport, msg_t *msg,
				    void *arg, su_time_t now);
static nth_site_t **site_get_host(nth_site_t **, char const *host, char const *port);
211 212 213
static nth_site_t **site_get_rslot(nth_site_t *parent, char *path,
				   char **return_rest);
static nth_site_t *site_get_subdir(nth_site_t *parent, char const *path, char const **res);
Pekka Pessi's avatar
Pekka Pessi committed
214 215 216
static void server_tport_error(server_t *srv, tport_t *tport,
			       int errcode, char const *remote);
static msg_t *server_msg_create(server_t *srv, int flags, 
217
				char const data[], usize_t dlen,
Pekka Pessi's avatar
Pekka Pessi committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
				tport_t const *tp, tp_client_t *tpc);

static void server_reply(server_t *srv, tport_t *tport, 
			 msg_t *request, msg_t *response,
			 int status, char const *phrase);

static
void nth_site_request(server_t *srv,
		      nth_site_t *site,
		      tport_t *tport,
		      msg_t *request,
		      http_t *http,
		      char const *path,
		      msg_t *response);

/* ----------------------------------------------------------------------
 * 5) Site functions
 */

/** Create a http site object. 
 *
 * The function nth_site_create() allocates and initializes a web site
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
 * object. A web site object can be either 
 * - a primary http server (@a parent is NULL),
 * - a virtual http server (@a address contains hostpart), or 
 * - a site within a server 
 *   (@a address does not have hostpart, only path part).
 *
 * @param parent pointer to parent site
 *               (NULL when creating a primary server object)
 * @param callback pointer to callback function called when
 *                 a request is received
 * @param magic    application context included in callback parameters
 * @param address  absolute or relative URI specifying the address of
 *                 site
 * @param tag, value, ... list of tagged parameters
 *
 * @TAGS
 * If the @a parent is NULL, the list of tagged parameters must contain
 * NTHTAG_ROOT() used to create the server engine. Tags supported when @a
 * parent is NULL are NTHTAG_ROOT(), NTHTAG_MCLASS(), TPTAG_REUSE(),
 * HTTPTAG_SERVER(), and HTTPTAG_SERVER_STR(). All the tags are passed to
 * tport_tcreate() and tport_tbind(), too.
 *
262
 * @since Support for multiple sites was added to @VERSION_1_12_4
Pekka Pessi's avatar
Pekka Pessi committed
263 264 265 266 267 268 269 270
 */
nth_site_t *nth_site_create(nth_site_t *parent,  
			    nth_request_f *callback,
			    nth_site_magic_t *magic,
			    url_string_t const *address,
			    tag_type_t tag, tag_value_t value,
			    ...)
{
271 272 273 274
  nth_site_t *site = NULL, **prev = NULL;
  su_home_t home[SU_HOME_AUTO_SIZE(256)];
  url_t *url, url0[1];
  server_t *srv = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
275
  ta_list ta;
276 277
  char *path = NULL;
  size_t usize;
278
  int is_host, is_path, wildcard = 0;
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

  su_home_auto(home, sizeof home);

  if (parent && url_is_string(address)) {
    char const *s = (char const *)address;
    size_t sep = strcspn(s, "/:");
    if (s[sep] == ':')
      /* absolute URL with scheme */;
    else if (s[sep] == '\0' && strchr(s, '.') && host_is_valid(s)) {
      /* looks like a domain name */;
      url_init(url0, parent->site_url->url_type);
      url0->url_host = s;
      address = (url_string_t*)url0;
    }
    else {
      /* looks like a path */
      url_init(url0, parent->site_url->url_type);
      url0->url_path = s;
      address = (url_string_t*)url0;
    }
  }
Pekka Pessi's avatar
Pekka Pessi committed
300

301
  url = url_hdup(home, address->us_url);
Pekka Pessi's avatar
Pekka Pessi committed
302 303 304

  if (!url || !callback)
    return NULL;
305 306 307
  
  is_host = url->url_host != NULL;
  is_path = url->url_path != NULL;
Pekka Pessi's avatar
Pekka Pessi committed
308

309
  if (is_host && is_path) {
Pekka Pessi's avatar
Pekka Pessi committed
310 311
    SU_DEBUG_3(("nth_site_create(): virtual host and path simultanously\n"));
    errno = EINVAL;
312
    goto error;
Pekka Pessi's avatar
Pekka Pessi committed
313 314
  }

315 316
  if (!parent && !is_host) {
    SU_DEBUG_3(("nth_site_create(): host is required\n"));
Pekka Pessi's avatar
Pekka Pessi committed
317
    errno = EINVAL;
318
    goto error;
Pekka Pessi's avatar
Pekka Pessi committed
319 320 321
  }

  if (parent) {
322 323 324 325 326 327
    if (!parent->site_isdir) {
      SU_DEBUG_3(("nth_site_create(): invalid parent resource \n"));
      errno = EINVAL;
      goto error;
    }
      
Pekka Pessi's avatar
Pekka Pessi committed
328
    srv = parent->site_server; assert(srv);
329
    if (is_host) {
Pekka Pessi's avatar
Pekka Pessi committed
330
      prev = site_get_host(&srv->srv_sites, url->url_host, url->url_port);
331 332 333 334 335 336 337 338

      if (prev == NULL) {
	SU_DEBUG_3(("nth_site_create(): host %s:%s already exists\n",
		    url->url_host, url->url_port ? url->url_port : ""));
	errno = EEXIST;
	goto error;
      }
    } 
Pekka Pessi's avatar
Pekka Pessi committed
339
    else {
340 341 342 343 344 345 346 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
      size_t i, j;

      path = (char *)url->url_path;
      while (path[0] == '/')
	path++;

      /* Remove duplicate // */
      for (i = j = 0; path[i];) {
	while (path[i] == '/' && path[i + 1] == '/')
	  i++;
	path[j++] = path[i++];
      }
      path[j] = path[i];

      url = url0, *url = *parent->site_url;

      if (url->url_path) {
	url->url_path = su_strcat(home, url->url_path, path);
	if (!url->url_path)
	  goto error;
	path = (char *)url->url_path + strlen(parent->site_url->url_path);
      }
      else
	url->url_path = path;

      prev = site_get_rslot(parent, path, &path);

      if (!prev || path[0] == '\0') {
	SU_DEBUG_3(("nth_site_create(): directory \"%s\" already exists\n", 
		    url->url_path));
	errno = EEXIST;
	goto error;
      }
Pekka Pessi's avatar
Pekka Pessi committed
373 374
    }
  }
375 376 377

  if (!parent) {
    if (strcmp(url->url_host, "*") == 0 ||
378 379 380
	host_cmp(url->url_host, "0.0.0.0") == 0 ||
	host_cmp(url->url_host, "::") == 0)
      wildcard = 1, url->url_host = "*";
381 382 383 384 385 386 387
  }

  usize = sizeof(*url) + url_xtra(url);

  ta_start(ta, tag, value);

  if (!parent) {
Pekka Pessi's avatar
Pekka Pessi committed
388 389 390 391
    srv = server_create(url, ta_tags(ta));
    prev = &srv->srv_sites;
  }

392 393 394 395
  if (srv && (site = su_zalloc(srv->srv_home, (sizeof *site) + usize))) {
    site->site_url = (url_t *)(site + 1);
    url_dup((void *)(site->site_url + 1), usize - sizeof(*url), 
	    site->site_url, url);
Pekka Pessi's avatar
Pekka Pessi committed
396

397 398
    assert(prev);
    if ((site->site_next = *prev))
Pekka Pessi's avatar
Pekka Pessi committed
399 400 401
      site->site_next->site_prev = &site->site_next;
    *prev = site, site->site_prev = prev;
    site->site_server = srv;
402

Pekka Pessi's avatar
Pekka Pessi committed
403
    if (path) {
404 405
      size_t path_len;

Pekka Pessi's avatar
Pekka Pessi committed
406
      site->site_path = site->site_url->url_path + (path - url->url_path);
407 408 409 410 411 412 413
      path_len = strlen(site->site_path); assert(path_len > 0);
      if (path_len > 0 && site->site_path[path_len - 1] == '/')
	path_len--, site->site_isdir = 1;
      site->site_path_len = path_len;
    }
    else {
      site->site_isdir = is_host;
Pekka Pessi's avatar
Pekka Pessi committed
414 415 416
      site->site_path = "";
      site->site_path_len = 0;
    }
417

418
    site->site_wildcard = wildcard;
Pekka Pessi's avatar
Pekka Pessi committed
419 420
    site->site_callback = callback;
    site->site_magic = magic;
421 422 423 424
    
    if (parent)
      site->site_auth = parent->site_auth;

Pekka Pessi's avatar
Pekka Pessi committed
425 426 427 428 429
    nth_site_set_params(site, ta_tags(ta));
  }

  ta_end(ta);

430 431
 error:
  su_home_deinit(home);
Pekka Pessi's avatar
Pekka Pessi committed
432 433 434 435 436
  return site;
}

void nth_site_destroy(nth_site_t *site)
{
437 438 439 440 441 442 443
  if (site == NULL)
    return;

  if (site->site_auth)
    auth_mod_unref(site->site_auth), site->site_auth = NULL;

  if (site->site_server->srv_sites == site) {
Pekka Pessi's avatar
Pekka Pessi committed
444 445 446 447
    server_destroy(site->site_server);
  }
}

448

Pekka Pessi's avatar
Pekka Pessi committed
449 450 451 452 453
nth_site_magic_t *nth_site_magic(nth_site_t const *site)
{
  return site ? site->site_magic : NULL;
}

454

Pekka Pessi's avatar
Pekka Pessi committed
455 456 457 458 459 460 461 462 463 464
void nth_site_bind(nth_site_t *site, 
		   nth_request_f *callback, 
		   nth_site_magic_t *magic)
{
  if (site) {
    site->site_callback = callback;
    site->site_magic = magic;
  }
}

465

Pekka Pessi's avatar
Pekka Pessi committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
char const *nth_site_server_version(void)
{
  return "nth/" NTH_VERSION;
}

int nth_site_set_params(nth_site_t *site,
			tag_type_t tag, tag_value_t value, ...)
{
  int n;
  ta_list ta;

  server_t *server;
  int master;
  msg_mclass_t const *mclass;
  int mflags;
481
  auth_mod_t *am;
Pekka Pessi's avatar
Pekka Pessi committed
482 483 484 485 486 487

  if (site == NULL)
    return (errno = EINVAL), -1;

  server = site->site_server;
  master = site == server->srv_sites;
488
  am = site->site_auth;
Pekka Pessi's avatar
Pekka Pessi committed
489 490 491 492 493 494 495 496 497

  mclass = server->srv_mclass;
  mflags = server->srv_mflags;

  ta_start(ta, tag, value);

  n = tl_gets(ta_args(ta),
	      TAG_IF(master, NTHTAG_MCLASS_REF(mclass)),
	      TAG_IF(master, NTHTAG_MFLAGS_REF(mflags)),
498
	      NTHTAG_AUTH_MODULE_REF(am),
Pekka Pessi's avatar
Pekka Pessi committed
499 500 501 502 503 504 505 506
	      TAG_END());
  
  if (n > 0) {
    if (mclass)
      server->srv_mclass = mclass;
    else
      server->srv_mclass = http_default_mclass();
    server->srv_mflags = mflags;
507
    auth_mod_ref(am), auth_mod_unref(site->site_auth), site->site_auth = am;
Pekka Pessi's avatar
Pekka Pessi committed
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 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  }

  ta_end(ta);

  return n;
}

int nth_site_get_params(nth_site_t const *site,
			tag_type_t tag, tag_value_t value, ...)
{
  int n;
  ta_list ta;
  server_t *server;
  int master;
  msg_mclass_t const *mclass;

  if (site == NULL)
    return (errno = EINVAL), -1;

  server = site->site_server;
  master = site == server->srv_sites;

  if (master && server->srv_mclass != http_default_mclass())
    mclass = server->srv_mclass;
  else
    mclass = NULL;

  ta_start(ta, tag, value);

  n = tl_tgets(ta_args(ta),
	       TAG_IF(master, NTHTAG_MCLASS(mclass)),
	       TAG_IF(master, NTHTAG_MFLAGS(server->srv_mflags)),
	       TAG_END());
  
  ta_end(ta);

  return n;
}

int nth_site_get_stats(nth_site_t const *site, 
		       tag_type_t tag, tag_value_t value, ...)
{
  int n;
  ta_list ta;

  if (site == NULL)
    return (errno = EINVAL), -1;

  ta_start(ta, tag, value);

  n = tl_tgets(ta_args(ta),
	       TAG_END());
  
  ta_end(ta);

  return n;
}

static
nth_site_t **site_get_host(nth_site_t **list, char const *host, char const *port)
{
  nth_site_t *site;

  assert(host);

  for (; (site = *list); list = &site->site_next) {
574
    if (host_cmp(host, site->site_url->url_host) == 0 &&
Pekka Pessi's avatar
Pekka Pessi committed
575 576 577 578 579 580 581 582
	str0cmp(port, site->site_url->url_port) == 0) {
      break;
    }
  }

  return list;
}

583 584 585 586 587
/** Find a place to insert site from the hierarchy.
 *
 * A resource can be either a 'dir' (name ends with '/') or 'file'.
 * When a resource
 */
Pekka Pessi's avatar
Pekka Pessi committed
588
static
589 590
nth_site_t **site_get_rslot(nth_site_t *parent, char *path, 
			    char **return_rest)
Pekka Pessi's avatar
Pekka Pessi committed
591 592
{
  nth_site_t *site, **prev;
593 594
  size_t len;
  int cmp;
Pekka Pessi's avatar
Pekka Pessi committed
595 596 597

  assert(path);

598 599
  if (path[0] == '\0')
    return errno = EEXIST, NULL;
Pekka Pessi's avatar
Pekka Pessi committed
600

601 602 603 604 605 606 607 608 609 610
  for (prev = &parent->site_kids; (site = *prev); prev = &site->site_next) {
    cmp = strncmp(path, site->site_path, len = site->site_path_len);
    if (cmp > 0)
      break;
    if (cmp < 0)
      continue;
    if (path[len] == '\0') {
      if (site->site_isdir)
	return *return_rest = path, prev; 
      return errno = EEXIST, NULL;
Pekka Pessi's avatar
Pekka Pessi committed
611
    }
612 613
    if (path[len] != '/' || site->site_path[len] != '/')
      continue;
Pekka Pessi's avatar
Pekka Pessi committed
614

615 616
    while (path[++len] == '/')
      ;
Pekka Pessi's avatar
Pekka Pessi committed
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 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    return site_get_rslot(site, path + len, return_rest);
  }

  *return_rest = path;

  return prev;
}

static char const site_nodir_match[] = "";

/** Find a subdir from site hierarchy */
static
nth_site_t *site_get_subdir(nth_site_t *parent,
			    char const *path,
			    char const **return_rest)
{
  nth_site_t *site;
  size_t len;
  int cmp;

  assert(path);

  while (path[0] == '/')	/* Skip multiple slashes */
    path++;

  if (path[0] == '\0')
    return *return_rest = path, parent;
  
  for (site = parent->site_kids; site; site = site->site_next) {
    cmp = strncmp(path, site->site_path, len = site->site_path_len);
    if (cmp > 0)
      break;
    if (cmp < 0)
      continue;
    if (path[len] == '\0')
      return *return_rest = site_nodir_match, site;
    if (site->site_path[len] == '/' && path[len] == '/')
      return site_get_subdir(site, path + len + 1, return_rest);
  }

  return *return_rest = path, parent;
Pekka Pessi's avatar
Pekka Pessi committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
}


/* ----------------------------------------------------------------------
 * Server functions
 */

static char const * const http_tports[] =
  {
    "tcp", "tls", NULL
  };

static tp_stack_class_t nth_server_class[1] =
  {{
    sizeof(nth_server_class),
    server_request,
    server_tport_error,
    server_msg_create
  }};

server_t *server_create(url_t const *url,
			tag_type_t tag, tag_value_t value, ...)
{
  server_t *srv;
  msg_mclass_t *mclass = NULL;
  tp_name_t tpn[1] = {{ NULL }};
  su_root_t *root = NULL;
  http_server_t const *server = NULL;
  int persistent = 0;
  char const *server_str = SERVER_VERSION;
  ta_list ta;

  ta_start(ta, tag, value);
  tl_gets(ta_args(ta), 
	  NTHTAG_ROOT_REF(root),
	  NTHTAG_MCLASS_REF(mclass),
	  TPTAG_REUSE_REF(persistent),
	  HTTPTAG_SERVER_REF(server),
	  HTTPTAG_SERVER_STR_REF(server_str),
	  TAG_END());

  if (!root || !url || 
      (url->url_type != url_http && url->url_type != url_https)
702
      || !(srv = su_home_new(sizeof(*srv)))) {
Pekka Pessi's avatar
Pekka Pessi committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    ta_end(ta);
    return NULL;
  }

  tpn->tpn_proto = url_tport_default(url->url_type);
  tpn->tpn_canon = url->url_host;
  tpn->tpn_host =  url->url_host;
  tpn->tpn_port = url_port(url);

  srv->srv_tports = tport_tcreate(srv, nth_server_class, root, 
				  TPTAG_IDLE(600000),
				  TPTAG_TIMEOUT(300000),
				  ta_tags(ta));

  srv->srv_persistent = persistent;
  srv->srv_max_bodylen = 1 << 30; /* 1 GB */

  if (tport_tbind(srv->srv_tports, tpn, http_tports,
		  TAG_END()) >= 0) {
    srv->srv_root = root;
    srv->srv_mclass = mclass ? mclass : http_default_mclass();
    srv->srv_mflags = MSG_DO_CANONIC;

    if (server)
      srv->srv_server = http_server_dup(srv->srv_home, server);
    else
      srv->srv_server = http_server_make(srv->srv_home, server_str);

    tport_get_params(srv->srv_tports,
		     TPTAG_QUEUESIZE_REF(srv->srv_queuesize),
		     TAG_END());
  }
  else {
    SU_DEBUG_1(("nth_server_create: cannot bind transports " 
		URL_FORMAT_STRING "\n",
		URL_PRINT_ARGS(url))); 
    server_destroy(srv), srv = NULL;
  }

  ta_end(ta);

  return srv;
}

void server_destroy(server_t *srv)
{
  tport_destroy(srv->srv_tports);
  su_timer_destroy(srv->srv_timer);
751
  su_home_unref(srv->srv_home);
Pekka Pessi's avatar
Pekka Pessi committed
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 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
}

/** Initialize server timer. */
static inline
int server_timer_init(server_t *srv)
{
  srv->srv_timer = su_timer_create(su_root_task(srv->srv_root), SERVER_TICK);
  return su_timer_set(srv->srv_timer, server_timer, srv);
}

/**
 * Server timer routine.
 */
static
void server_timer(su_root_magic_t *rm, su_timer_t *timer, server_t *srv)
{
  uint32_t now;

  su_timer_set(timer, server_timer, srv);

  now = su_time_ms(su_now()); now += now == 0; srv->srv_now = now;

  /* Xyzzy */

  srv->srv_now = 0;
}

/** Get current timestamp in milliseconds */
static inline
uint32_t server_now(server_t const *srv)
{
  if (srv->srv_now)
    return srv->srv_now;
  else
    return su_time_ms(su_now());
}


/** Process incoming request message */
static
void server_request(server_t *srv,
		    tport_t *tport,
		    msg_t *request,
		    void *arg,
		    su_time_t now)
{
798
  nth_site_t *site = NULL, *subsite = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
799 800 801
  msg_t *response;
  http_t *http = http_object(request);
  http_host_t *h;
802
  char const *host, *port, *path, *subpath = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854

  /* Disable streaming */
  if (msg_is_streaming(request)) {
    msg_set_streaming(request, 0);
    return;
  }

  /* Create a response message */
  response = server_msg_create(srv, 0, NULL, 0, NULL, NULL);
  tport_tqueue(tport, response, TAG_END());

  if (http && http->http_flags & MSG_FLG_TIMEOUT) {
    server_reply(srv, tport, request, response, 400, "Request timeout");
    return;
  } else if (http && http->http_flags & MSG_FLG_TOOLARGE) {
    server_reply(srv, tport, request, response, HTTP_413_ENTITY_TOO_LARGE);
    return;
  } else if (!http || !http->http_request || 
	     (http->http_flags & MSG_FLG_ERROR)) {
    server_reply(srv, tport, request, response, HTTP_400_BAD_REQUEST);
    return;
  }

  if (http->http_request->rq_version != http_version_1_0 &&
      http->http_request->rq_version != http_version_1_1) {
    server_reply(srv, tport, request, response, HTTP_505_HTTP_VERSION);
    return;
  }

  h = http->http_host;

  if (h) {
    host = h->h_host, port = h->h_port;
  }
  else if (http->http_request->rq_url->url_host) {
    host = http->http_request->rq_url->url_host;
    port = http->http_request->rq_url->url_port;
  }
  else
    host = NULL, port = NULL;

  path = http->http_request->rq_url->url_path;

  if (host)
    site = *site_get_host(&srv->srv_sites, host, port);

  if (site == NULL && !srv->srv_sites->site_strict)
    site = srv->srv_sites;

  if (path == NULL)
    path = "";

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
  if (path[0])
    subsite = site_get_subdir(site, path, &subpath);

  if (subsite && subsite->site_isdir && subpath == site_nodir_match) {
    /* Answer with 301 */
    http_location_t loc[1];
    http_location_init(loc);

    *loc->loc_url = *site->site_url;

    if (site->site_wildcard) {
      if (http->http_host) {
	loc->loc_url->url_host = http->http_host->h_host;
	loc->loc_url->url_port = http->http_host->h_port;
      }
      else {
	tp_name_t const *tpn = tport_name(tport); assert(tpn);
	loc->loc_url->url_host = tpn->tpn_canon;
	if (strcmp(url_port_default(loc->loc_url->url_type), tpn->tpn_port))
	  loc->loc_url->url_port = tpn->tpn_port;
      }
    }

    loc->loc_url->url_root = 1;
    loc->loc_url->url_path = subsite->site_url->url_path;

    msg_header_add_dup(response, NULL, (msg_header_t *)loc);
      
    server_reply(srv, tport, request, response, HTTP_301_MOVED_PERMANENTLY);
  }
  else if (subsite)
    nth_site_request(srv, subsite, tport, request, http, subpath, response);
  else if (site)
Pekka Pessi's avatar
Pekka Pessi committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 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
    nth_site_request(srv, site, tport, request, http, path, response);
  else
    /* Answer with 404 */
    server_reply(srv, tport, request, response, HTTP_404_NOT_FOUND);
}

static void server_tport_error(server_t *srv,
				   tport_t *tport,
				   int errcode,
				   char const *remote)
{
  su_log("\nth: tport: %s%s%s\n",
	 remote ? remote : "", remote ? ": " : "",
	 su_strerror(errcode));
}

/** Respond without creating a request structure */
static void server_reply(server_t *srv, tport_t *tport, 
			 msg_t *request, msg_t *response,
			 int status, char const *phrase)
{
  http_t *http;
  http_payload_t *pl;
  int close;
  http_status_t st[1];
  char const *req_version = NULL;

  if (status < 200 || status >= 600)
    status = 500, phrase = http_500_internal_server;

  http = http_object(request);
  
  if (http && http->http_request)
    req_version = http->http_request->rq_version;

  close = status >= 200 && 
    (!srv->srv_persistent
     || status == 400
     || (http && http->http_request && 
	 http->http_request->rq_version != http_version_1_1)
     || (http && http->http_connection && 
	 msg_params_find(http->http_connection->k_items, "close")));

  msg_destroy(request);

  http = http_object(response);

  pl = http_payload_format(msg_home(response), 
			   "<html>\n"
			   "<head><title>%u %s</title></head>\n"
			   "<body><h2>%u %s</h2></body>\n"
			   "</html>\n", status, phrase, status, phrase);

  msg_header_insert(response, (msg_pub_t *)http, (msg_header_t *)pl);

  if (req_version != http_version_0_9) {
    http_status_init(st);
    st->st_version = http_version_1_1;
    st->st_status = status;
    st->st_phrase = phrase;
    
    http_add_tl(response, http,
		HTTPTAG_STATUS(st),
		HTTPTAG_SERVER(srv->srv_server),
		HTTPTAG_CONTENT_TYPE_STR("text/html"),
		HTTPTAG_SEPARATOR_STR("\r\n"),
		TAG_IF(close, HTTPTAG_CONNECTION_STR("close")),
		TAG_END());

    msg_serialize(response, (msg_pub_t *)http);
  } else {
    /* Just send the response */
    *msg_chain_head(response) = (msg_header_t *)pl;
    close = 1;
  }

  if (tport_tqsend(tport, response, NULL, 
		   TPTAG_CLOSE_AFTER(close), 
		   TAG_END()) == -1) {
    SU_DEBUG_3(("server_reply(): cannot queue response\n"));
    tport_shutdown(tport, 2);
  }

  msg_destroy(response);
}

/** Create a new message for transport */
static
msg_t *server_msg_create(server_t *srv, int flags, 
977
			 char const data[], usize_t dlen,
Pekka Pessi's avatar
Pekka Pessi committed
978 979 980 981 982 983 984 985 986 987 988
			 tport_t const *tp, tp_client_t *tpc)
{
  msg_t *msg = msg_create(srv->srv_mclass, srv->srv_mflags | flags);

  return msg;
}

/* ----------------------------------------------------------------------
 * 6) Server transactions 
 */

989 990 991 992 993 994 995 996 997 998
struct auth_info
{
  nth_site_t *site;
  nth_request_t *req;
  http_t const *http;
  char const *path;
};

static void nth_authentication_result(void *ai0, auth_status_t *as);

Pekka Pessi's avatar
Pekka Pessi committed
999 1000 1001 1002 1003 1004 1005 1006 1007
static
void nth_site_request(server_t *srv,
		      nth_site_t *site,
		      tport_t *tport,
		      msg_t *request,
		      http_t *http,
		      char const *path,
		      msg_t *response)
{
1008 1009 1010 1011 1012
  auth_mod_t *am = site->site_auth;
  nth_request_t *req;
  auth_status_t *as;
  struct auth_info *ai;
  size_t size = (am ? (sizeof *as) + (sizeof *ai) : 0) + (sizeof *req);
Pekka Pessi's avatar
Pekka Pessi committed
1013 1014
  int status;

1015 1016
  req = su_zalloc(srv->srv_home, size);
  
Pekka Pessi's avatar
Pekka Pessi committed
1017 1018 1019 1020 1021
  if (req == NULL) {
    server_reply(srv, tport, request, response, HTTP_500_INTERNAL_SERVER);
    return;
  }
  
1022 1023 1024 1025 1026
  if (am)
    as = auth_status_init(req + 1, sizeof *as), ai = (void *)(as + 1);
  else
    as = NULL, ai = NULL;

Pekka Pessi's avatar
Pekka Pessi committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
  req->req_server = srv;
  req->req_method = http->http_request->rq_method;
  req->req_method_name = http->http_request->rq_method_name;
  req->req_url = http->http_request->rq_url;
  req->req_version = http->http_request->rq_version;

  req->req_tport = tport_incref(tport);
  req->req_request = request;
  req->req_response = response;

  req->req_status = 100;
  req->req_close = 
    !srv->srv_persistent
    || http->http_request->rq_version != http_version_1_1
    || (http->http_connection && 
	msg_params_find(http->http_connection->k_items, "close"));

1044 1045 1046 1047 1048 1049 1050 1051 1052 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
  if (am) {
    static auth_challenger_t const http_server_challenger[] = 
      {{ HTTP_401_UNAUTHORIZED, http_www_authenticate_class }};

    req->req_as = as;

    as->as_method = http->http_request->rq_method_name;
    as->as_uri = path;
    
    if (http->http_payload) {
      as->as_body = http->http_payload->pl_data;
      as->as_bodylen = http->http_payload->pl_len;
    }

    auth_mod_check_client(am, as, 
			  http->http_authorization,
			  http_server_challenger);

    if (as->as_status == 100) {
      /* Stall transport - do not read more requests */
      if (tport_queuelen(tport) * 2 >= srv->srv_queuesize)
	tport_stall(tport);

      as->as_callback = nth_authentication_result;
      as->as_magic = ai;
      ai->site = site;
      ai->req = req;
      ai->http = http;
      ai->path = path;
      return;
    }
    else if (as->as_status) {
      assert(as->as_status >= 200);
      nth_request_treply(req, as->as_status, as->as_phrase,
			 HTTPTAG_HEADER((http_header_t *)as->as_response),
			 HTTPTAG_HEADER((http_header_t *)as->as_info),
			 TAG_END());
      nth_request_destroy(req);
      return;
    }
  }

Pekka Pessi's avatar
Pekka Pessi committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  req->req_in_callback = 1;
  status = site->site_callback(site->site_magic, site, req, http, path);
  req->req_in_callback = 0;

  if (status != 0 && (status < 100 || status >= 600))
    status = 500;

  if (status != 0 && req->req_status < 200) {
    nth_request_treply(req, status, NULL, TAG_END());
  }

  if (req->req_status < 100) {
    /* Stall transport - do not read more requests */
    if (tport_queuelen(tport) * 2 >= srv->srv_queuesize)
      tport_stall(tport);
  }

  if (status >= 200 || req->req_destroyed)
    nth_request_destroy(req);
}

1107 1108 1109 1110 1111 1112 1113
static void nth_authentication_result(void *ai0, auth_status_t *as)
{
  struct auth_info *ai = ai0;
  nth_request_t *req = ai->req;
  int status;

  if (as->as_status != 0) {
1114
    assert(as->as_status >= 300);
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
    nth_request_treply(req, status = as->as_status, as->as_phrase, 
		       HTTPTAG_HEADER((http_header_t *)as->as_response), 
		       TAG_END());
  }
  else {
    req->req_in_callback = 1;
    status = ai->site->site_callback(ai->site->site_magic, 
				     ai->site,
				     ai->req,
				     ai->http,
				     ai->path);
    req->req_in_callback = 0;

    if (status != 0 && (status < 100 || status >= 600))
      status = 500;

    if (status != 0 && req->req_status < 200) {
      nth_request_treply(req, status, NULL, TAG_END());
    }
  }

  if (status >= 200 || req->req_destroyed)
    nth_request_destroy(req);
}

Pekka Pessi's avatar
Pekka Pessi committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
void nth_request_destroy(nth_request_t *req)
{
  if (req == NULL)
    return;

  if (req->req_status < 200)
    nth_request_treply(req, HTTP_500_INTERNAL_SERVER, TAG_END());

  req->req_destroyed = 1;

  if (req->req_in_callback) 
    return;

1153 1154 1155 1156
  if (req->req_as)
    su_home_deinit(req->req_as->as_home);

  tport_decref(&req->req_tport), req->req_tport = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1157 1158 1159 1160 1161
  msg_destroy(req->req_request), req->req_request = NULL;
  msg_destroy(req->req_response), req->req_response = NULL;
  su_free(req->req_server->srv_home, req);
}

1162 1163 1164 1165 1166 1167 1168 1169
/** Return request authentication status.
 *
 * @param req pointer to HTTP request object
 * 
 * @retval Status code
 *
 * @since New in @VERSION_1_12_4
 */
Pekka Pessi's avatar
Pekka Pessi committed
1170 1171 1172 1173 1174
int nth_request_status(nth_request_t const *req)
{
  return req ? req->req_status : 400;
}

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
/** Return request authentication status.
 *
 * @param req pointer to HTTP request object
 * 
 * @retval Pointer to authentication status struct
 *
 * @note The authentication status struct is freed when the #nth_request_t
 * object is destroyed.
 *
 * @since New in @VERSION_1_12_4
 *
 * @sa AUTH
 */
1188 1189 1190 1191 1192
auth_status_t *nth_request_auth(nth_request_t const *req)
{
  return req ? req->req_as : NULL;
}

Pekka Pessi's avatar
Pekka Pessi committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
http_method_t nth_request_method(nth_request_t const *req)
{
  return req ? req->req_method : http_method_invalid;
}

msg_t *nth_request_message(nth_request_t *req)
{
  msg_t *retval = NULL;

  if (req)
    retval = msg_ref_create(req->req_request);

  return retval;
}

int nth_request_treply(nth_request_t *req, 
		       int status, char const *phrase, 
		       tag_type_t tag, tag_value_t value, ...)
{
  msg_t *response, *next = NULL;
  http_t *http;
  int retval = -1;
  int req_close, close;
  ta_list ta;
1217 1218
  http_header_t const *as_info = NULL;

Pekka Pessi's avatar
Pekka Pessi committed
1219 1220 1221 1222 1223 1224 1225
  if (req == NULL || status < 100 || status >= 600) {
    return -1;
  }

  response = req->req_response;
  http = http_object(response);

1226 1227 1228
  if (status >= 200 && req->req_as)
    as_info = (http_header_t const *)req->req_as->as_info;

Pekka Pessi's avatar
Pekka Pessi committed
1229 1230 1231 1232
  ta_start(ta, tag, value);

  http_add_tl(response, http,
	      HTTPTAG_SERVER(req->req_server->srv_server),
1233
	      HTTPTAG_HEADER(as_info), 
Pekka Pessi's avatar
Pekka Pessi committed
1234 1235 1236 1237 1238
	      ta_tags(ta));

  if (http->http_payload && !http->http_content_length) {
    http_content_length_t *l;
    http_payload_t *pl;
1239
    size_t len = 0;
Pekka Pessi's avatar
Pekka Pessi committed
1240 1241 1242 1243
    
    for (pl = http->http_payload; pl; pl = pl->pl_next)
      len += pl->pl_len;

1244 1245 1246 1247
    if (len > UINT32_MAX)
      goto fail;

    l = http_content_length_create(msg_home(response), (uint32_t)len);
Pekka Pessi's avatar
Pekka Pessi committed
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

    msg_header_insert(response, (msg_pub_t *)http, (msg_header_t *)l);
  }

  if (req->req_method == http_method_head && http->http_payload) {
    http_payload_t *pl;
    
    for (pl = http->http_payload; pl; pl = pl->pl_next)
      msg_header_remove(response, (msg_pub_t *)http, (msg_header_t *)pl);
  }

  http_complete_response(response, status, phrase, 
			 http_object(req->req_request));

  if (!http->http_date) {
    http_date_t date[1];
    http_date_init(date)->d_time = msg_now();
    msg_header_add_dup(response, (msg_pub_t *)http, (msg_header_t*)date);
  }

  if (status < 200) {
    close = 0;
    next = server_msg_create(req->req_server, 0, NULL, 0, NULL, NULL);
  }
  else {
    req_close = req->req_close;

    close = (http->http_connection && 
	     msg_params_find(http->http_connection->k_items, "close"));
    
    if (req_close && !close && status >= 200) {
      close = 1;
      http_add_tl(response, http, HTTPTAG_CONNECTION_STR("close"), TAG_END());
    }
  }

  msg_serialize(response, (msg_pub_t *)http);

  retval = tport_tqsend(req->req_tport, response, next, 
			TAG_IF(close, TPTAG_CLOSE_AFTER(1)),
			ta_tags(ta));

1290
 fail:
Pekka Pessi's avatar
Pekka Pessi committed
1291 1292 1293 1294 1295 1296 1297
  ta_end(ta);
  
  if (retval == 0)
    req->req_status = status;

  return retval;
}