<commit_before>/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: <NAME> <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * 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
 *
 */

/**@CFILE nua_stack.c
 * @brief Sofia-SIP User Agent Engine implementation
 *
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 *
 * @date Created: Wed Feb 14 18:32:58 2001 ppessi
 */

#include "config.h"

#include <sofia-sip/su_tag_class.h>
#include <sofia-sip/su_tag_class.h>
#include <sofia-sip/su_tagarg.h>
#include <sofia-sip/su_strlst.h>
#include <sofia-sip/su_uniqueid.h>

#include <sofia-sip/su_tag_io.h>

#define SU_ROOT_MAGIC_T   struct nua_s
#define SU_MSG_ARG_T      struct event_s

#define NUA_SAVED_EVENT_T su_msg_t *

#define NTA_AGENT_MAGIC_T    struct nua_s
#define NTA_LEG_MAGIC_T      struct nua_handle_s
#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
#define NTA_INCOMING_MAGIC_T struct nua_handle_s

#include <sofia-sip/sip.h>
#include <sofia-sip/sip_header.h>
#include <sofia-sip/sip_status.h>
#include <sofia-sip/sip_util.h>

#include <sofia-sip/tport_tag.h>
#include <sofia-sip/nta.h>
#include <sofia-sip/nta_tport.h>
#include <sofia-sip/auth_client.h>

#include <sofia-sip/soa.h>

#include "sofia-sip/nua.h"
#include "sofia-sip/nua_tag.h"
#include "nua_stack.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>

#include <assert.h>

/* ========================================================================
 *
 *                       Protocol stack side
 *
 * ======================================================================== */

nua_handle_t *nh_create(nua_t *nua, tag_type_t t, tag_value_t v, ...);
static void nh_append(nua_t *nua, nua_handle_t *nh);
static void nh_remove(nua_t *nua, nua_handle_t *nh);

static int nh_authorize(nua_handle_t *nh,
			tag_type_t tag, tag_value_t value, ...);

static int nh_challenge(nua_handle_t *nh, sip_t const *sip);

static void nua_stack_timer(nua_t *nua, su_timer_t *t, su_timer_arg_t *a);

/* ---------------------------------------------------------------------- */
/* Constant data */

/**@internal Default internal error. */
char const nua_internal_error[] = "Internal NUA Error";

char const nua_application_sdp[] = "application/sdp";

#define NUA_STACK_TIMER_INTERVAL (1000)

/* ----------------------------------------------------------------------
 * Initialization & deinitialization
 */

int nua_stack_init(su_root_t *root, nua_t *nua)
{
  su_home_t *home;

  nua_handle_t *dnh;
  int media_enable = 1;
  soa_session_t *soa = NULL;
  char const *soa_name = NULL;

  static int initialized_logs = 0;

  enter;

  if (!initialized_logs) {
    extern su_log_t tport_log[];
    extern su_log_t nta_log[];
    extern su_log_t nea_log[];
    extern su_log_t iptsec_log[];

    su_log_init(tport_log);
    su_log_init(nta_log);
    su_log_init(nea_log);
    su_log_init(iptsec_log);

    initialized_logs = 1;
  }

  nua->nua_root = root;

  home = nua->nua_home;
  nua->nua_handles_tail = &nua->nua_handles;
  sip_from_init(nua->nua_from);

  dnh = su_home_clone(nua->nua_home, sizeof (*dnh) + sizeof(*dnh->nh_prefs));
  if (!dnh)
    return -1;

  dnh->nh_prefs = (void *)(dnh + 1);
  dnh->nh_valid = nua_handle;
  dnh->nh_nua = nua;
  nua_handle_ref(dnh); dnh->nh_ref_by_stack = 1; 
  nua_handle_ref(dnh); dnh->nh_ref_by_user = 1;
  nh_append(nua, dnh);
  dnh->nh_ds->ds_local = nua->nua_from;
  dnh->nh_ds->ds_remote = nua->nua_from;

  if (nua_stack_set_defaults(dnh, dnh->nh_prefs) < 0)
    return -1;

  if (nua_stack_init_instance(dnh, nua->nua_args) < 0)
    return -1;

  nua->nua_invite_accept = sip_accept_make(home, SDP_MIME_TYPE);

  nua->nua_nta = nta_agent_create(root, NONE, NULL, NULL,
				  NTATAG_MERGE_482(1),
				  NTATAG_CLIENT_RPORT(1),
				  NTATAG_UA(1),
#if HAVE_SOFIA_SMIME
				  NTATAG_SMIME(nua->sm),
#endif
				  TPTAG_STUN_SERVER(1),
				  TAG_NEXT(nua->nua_args));

  dnh->nh_ds->ds_leg = nta_leg_tcreate(nua->nua_nta,
				       nua_stack_process_request, dnh,
				       NTATAG_NO_DIALOG(1),
				       TAG_END());

  if (nua->nua_nta == NULL ||
      dnh->nh_ds->ds_leg == NULL || 
      nta_agent_set_params(nua->nua_nta, NTATAG_UA(1), TAG_END()) < 0 ||
      nua_stack_init_transport(nua, nua->nua_args) < 0) {
    SU_DEBUG_1(("nua: initializing SIP stack failed\n"));
  }

  if (nua_stack_set_from(nua, 1, nua->nua_args) < 0)
    return -1;

  /* Set initial nta/soa parameters */
  if (tl_gets(nua->nua_args,
	      NUTAG_MEDIA_ENABLE_REF(media_enable),
	      NUTAG_SOA_NAME_REF(soa_name),
	      TAG_NULL()) < 0)
    return -1;

  nua->nua_media_enable = media_enable;
  
  if (media_enable) {
    if (soa == NULL)
      soa = soa_create(soa_name, nua->nua_root, nua->nua_dhandle);
    dnh->nh_soa = soa;
    soa_set_params(soa, TAG_NEXT(nua->nua_args));
  }

  nua->nua_timer = su_timer_create(su_root_task(root),
				   NUA_STACK_TIMER_INTERVAL);

  if (!nua->nua_timer)
    return -1;

  nua_stack_timer(nua, nua->nua_timer, NULL);

  nua->nua_args = NULL;

  return 0;
}

void nua_stack_deinit(su_root_t *root, nua_t *nua)
{
  enter;

  su_timer_destroy(nua->nua_timer), nua->nua_timer = NULL;
  nta_agent_destroy(nua->nua_nta), nua->nua_nta = NULL;
}

/* ----------------------------------------------------------------------
 * Sending events to client application
 */

static void nua_stack_shutdown(nua_t *);

void
  nua_stack_authenticate(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_respond(nua_t *, nua_handle_t *, int , char const *, tagi_t const *),
  nua_stack_destroy_handle(nua_t *, nua_handle_t *, tagi_t const *);

/* Notifier */
void
  nua_stack_authorize(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_notifier(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_terminate(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *);

int nh_notifier_shutdown(nua_handle_t *nh, nea_event_t *ev,
			 tag_type_t t, tag_value_t v, ...);

/** @internal Send an event to the application. */
int nua_stack_event(nua_t *nua, nua_handle_t *nh, msg_t *msg,
		    nua_event_t event, int status, char const *phrase,
		    tag_type_t tag, tag_value_t value, ...)
{
  su_msg_r sumsg = SU_MSG_R_INIT;

  ta_list ta;
  int e_len, len, xtra, p_len;

  enter;

  if (nua_log->log_level >= 5) {
    char const *name = nua_event_name(event) + 4;
    char const *p = phrase ? phrase : "";

    if (status == 0)
      SU_DEBUG_5(("nua(%p): %s %s\n", nh, name, p));
    else
      SU_DEBUG_5(("nua(%p): %s %u %s\n", nh, name, status, p));
  }

  if (event == nua_r_destroy) {
    if (msg)
      msg_destroy(msg);
    if (status >= 200) {
      nh_destroy(nua, nh);
    }
    return event;
  }

  if (event > nua_r_method || (nh && !nh->nh_valid) ||
      (nua->nua_shutdown && event != nua_r_shutdown)) {
    if (msg)
      msg_destroy(msg);
    return event;
  }

  ta_start(ta, tag, value);

  e_len = offsetof(event_t, e_tags);
  len = tl_len(ta_args(ta));
  xtra = tl_xtra(ta_args(ta), len);
  p_len = phrase ? strlen(phrase) + 1 : 1;

  if (su_msg_create(sumsg, nua->nua_client, nua->nua_server,
		    nua_event, e_len + len + xtra + p_len) == 0) {
    event_t *e = su_msg_data(sumsg);

    tagi_t *t = e->e_tags, *t_end = (tagi_t *)((char *)t + len);
    void *b = t_end, *end = (char *)b + xtra;

    t = tl_dup(t, ta_args(ta), &b);
    assert(t == t_end); assert(b == end);

    e->e_event = event;
    e->e_nh = nh ? nua_handle_ref(nh) : nua->nua_dhandle;
    e->e_status = status;
    e->e_phrase = strcpy(end, phrase ? phrase : "");
    e->e_msg = msg;

    if (su_msg_send(sumsg) != 0)
      nua_handle_unref(nh);
  }

  ta_end(ta);

  return event;
}

/* ----------------------------------------------------------------------
 * Post signal to stack itself
 */
void nua_stack_post_signal(nua_handle_t *nh, nua_event_t event,
			   tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  ta_start(ta, tag, value);
  nua_signal((nh)->nh_nua, nh, NULL, 1, event, 0, NULL, ta_tags(ta));
  ta_end(ta);
}


/* ----------------------------------------------------------------------
 * Receiving events from client
 */
void nua_stack_signal(nua_t *nua, su_msg_r msg, nua_event_data_t *e)
{
  nua_handle_t *nh = e->e_nh;
  tagi_t *tags = e->e_tags;

  assert(tags);

  if (nh) {
    if (!nh->nh_prev)
      nh_append(nua, nh);
    if (!nh->nh_ref_by_stack) {
      nh->nh_ref_by_stack = 1;
      nua_handle_ref(nh);
    }
  }

  if (nua_log->log_level >= 5) {
    char const *name = nua_event_name(e->e_event);
    if (e->e_status == 0)
      SU_DEBUG_5(("nua(%p): signal %s\n", nh, name + 4));
    else
      SU_DEBUG_5(("nua(%p): signal %s %u %s\n",
		  nh, name + 4, e->e_status, e->e_phrase ? e->e_phrase : ""));
  }

  su_msg_save(nua->nua_signal, msg);

  if (nua->nua_shutdown && !e->e_always) {
    /* Shutting down */
    nua_stack_event(nua, nh, NULL, e->e_event,
		    901, "Stack is going down",
		    TAG_END());
  }
  else switch (e->e_event) {
  case nua_r_get_params:
    nua_stack_get_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
    break;
  case nua_r_set_params:
    nua_stack_set_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
    break;
  case nua_r_shutdown:
    nua_stack_shutdown(nua);
    break;
  case nua_r_register:
  case nua_r_unregister:
    nua_stack_register(nua, nh, e->e_event, tags);
    break;
  case nua_r_invite:
    nua_stack_invite(nua, nh, e->e_event, tags);
    break;
  case nua_r_cancel:
    nua_stack_cancel(nua, nh, e->e_event, tags);
    break;
  case nua_r_bye:
    nua_stack_bye(nua, nh, e->e_event, tags);
    break;
  case nua_r_options:
    nua_stack_options(nua, nh, e->e_event, tags);
    break;
  case nua_r_refer:
    nua_stack_refer(nua, nh, e->e_event, tags);
    break;
  case nua_r_publish:
  case nua_r_unpublish:
    nua_stack_publish(nua, nh, e->e_event, tags);
    break;
  case nua_r_info:
    nua_stack_info(nua, nh, e->e_event, tags);
    break;
  case nua_r_update:
    nua_stack_update(nua, nh, e->e_event, tags);
    break;
  case nua_r_message:
    nua_stack_message(nua, nh, e->e_event, tags);
    break;
  case nua_r_subscribe:
  case nua_r_unsubscribe:
    nua_stack_subscribe(nua, nh, e->e_event, tags);
    break;
  case nua_r_notify:
    nua_stack_notify(nua, nh, e->e_event, tags);
    break;
  case nua_r_notifier:
    nua_stack_notifier(nua, nh, e->e_event, tags);
    break;
  case nua_r_terminate:
    nua_stack_terminate(nua, nh, e->e_event, tags);
    break;
  case nua_r_method:
    nua_stack_method(nua, nh, e->e_event, tags);
    break;
  case nua_r_authenticate:
    nua_stack_authenticate(nua, nh, e->e_event, tags);
    break;
  case nua_r_authorize:
    nua_stack_authorize(nua, nh, e->e_event, tags);
    break;
  case nua_r_ack:
    nua_stack_ack(nua, nh, e->e_event, tags);
    break;
  case nua_r_respond:
    nua_stack_respond(nua, nh, e->e_status, e->e_phrase, tags);
    break;
  case nua_r_destroy:
    nua_stack_destroy_handle(nua, nh, tags);
    break;
  default:
    break;
  }

  if (su_msg_is_non_null(nua->nua_signal))
    su_msg_destroy(nua->nua_signal);

  if (nh != nua->nua_dhandle)
    nua_handle_unref(nh);
}

/* ====================================================================== */

static int nh_call_pending(nua_handle_t *nh, sip_time_t time);

/**@internal
 * Timer routine.
 *
 * Go through all active handles and execute pending tasks
 */
void nua_stack_timer(nua_t *nua, su_timer_t *t, su_timer_arg_t *a)
{
  nua_handle_t *nh, *nh_next;
  sip_time_t now = sip_now();
  su_root_t *root = su_timer_root(t);

  su_timer_set(t, nua_stack_timer, a);

  if (nua->nua_shutdown) {
    nua_stack_shutdown(nua);
    return;
  }

  for (nh = nua->nua_handles; nh; nh = nh_next) {
    nh_next = nh->nh_next;
    nh_call_pending(nh, now);
    su_root_yield(root);	/* Handle received packets */
  }
}


static
int nh_call_pending(nua_handle_t *nh, sip_time_t now)
{
  nua_dialog_usage_t *du;
  sip_time_t next = now + NUA_STACK_TIMER_INTERVAL / 1000;

  for (du = nh->nh_ds->ds_usage; du; du = du->du_next) {
    if (now == 0)
      break;
    if (du->du_refresh && du->du_refresh < next)
      break;
  }

  if (du == NULL)
    return 0;

  nua_handle_ref(nh);

  while (du) {
    nua_dialog_usage_t *du_next = du->du_next;

    nua_dialog_usage_refresh(nh, du, now);

    if (du_next == NULL)
      break;

    for (du = nh->nh_ds->ds_usage; du; du = du->du_next)
      if (du == du_next)
	break;

    for (; du; du = du->du_next) {
      if (now == 0)
	break;
      if (du->du_refresh && du->du_refresh < next)
	break;
    }
  }

  nua_handle_unref(nh);

  return 1;
}


/* ====================================================================== */

/** @internal Shut down stack. */
void nua_stack_shutdown(nua_t *nua)
{
  nua_handle_t *nh, *nh_next;
  int busy = 0;
  sip_time_t now = sip_now();
  int status;
  char const *phrase;
  struct nua_session_state *ss;

  enter;

  if (!nua->nua_shutdown)
    nua->nua_shutdown = now;

  for (nh = nua->nua_handles; nh; nh = nh_next) {
    nh_next = nh->nh_next;

    ss = nh->nh_ss;

    if (ss->ss_srequest->sr_respond) {
      ss->ss_srequest->sr_respond(nua, nh, SIP_410_GONE, NULL);
      busy++;
    }

    busy += nh_call_pending(nh, 0);

    if (nh->nh_soa) {
      soa_destroy(nh->nh_soa), nh->nh_soa = NULL;
    }

    if (nh->nh_cr->cr_orq || nh->nh_ss->ss_crequest->cr_orq)
      busy++;

    if (nh_notifier_shutdown(nh, NULL, NEATAG_REASON("noresource"), TAG_END()))
      busy++;
  }

  if (!busy)
    SET_STATUS(200, "Shutdown successful");
  else if (now == nua->nua_shutdown)
    SET_STATUS(100, "Shutdown started");
  else if (now - nua->nua_shutdown < 30)
    SET_STATUS(101, "Shutdown in progress");
  else
    SET_STATUS(500, "Shutdown timeout");

  if (status >= 200) {
    for (nh = nua->nua_handles; nh; nh = nh_next) {
      nh_next = nh->nh_next;
      while (nh->nh_ds && nh->nh_ds->ds_usage) {
	nua_dialog_usage_remove(nh, nh->nh_ds, nh->nh_ds->ds_usage);
      }
    }
    su_timer_destroy(nua->nua_timer), nua->nua_timer = NULL;
    nta_agent_destroy(nua->nua_nta), nua->nua_nta = NULL;
  }

  nua_stack_event(nua, NULL, NULL, nua_r_shutdown, status, phrase, TAG_END());
}

/* ---------------------------------------------------------------------- */

/** @internal Create a handle */
nua_handle_t *nh_create(nua_t *nua, tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  nua_handle_t *nh;

  enter;

  ta_start(ta, tag, value);
  nh = nh_create_handle(nua, NULL, ta_args(ta));
  ta_end(ta);

  if (nh) {
    nh->nh_ref_by_stack = 1;
    nh_append(nua, nh);
  }

  return nh;
}

/** @internal Append an handle to the list of handles */
void nh_append(nua_t *nua, nua_handle_t *nh)
{
  nh->nh_next = NULL;
  nh->nh_prev = nua->nua_handles_tail;
  *nua->nua_handles_tail = nh;
  nua->nua_handles_tail = &nh->nh_next;
}

nua_handle_t *nh_validate(nua_t *nua, nua_handle_t *maybe)
{
  nua_handle_t *nh;

  if (maybe)
    for (nh = nua->nua_handles; nh; nh = nh->nh_next)
      if (nh == maybe)
	return nh;

  return NULL;
}

void nua_stack_destroy_handle(nua_t *nua, nua_handle_t *nh, tagi_t const *tags)
{
  nh_call_pending(nh, 0);	/* Call pending operations with 0 */

  if (nh->nh_notifier)
    nua_stack_terminate(nua, nh, 0, NULL);

#if 0
  if (nh->nh_ref_by_user) {
    nh->nh_ref_by_user = 0;
    nua_handle_unref(nh);
  }
#endif

  nh_destroy(nua, nh);
}

#define nh_is_inserted(nh) ((nh)->nh_prev != NULL)

/** @internal Remove a handle from list of handles */
static
void nh_remove(nua_t *nua, nua_handle_t *nh)
{
  assert(nh_is_inserted(nh)); assert(*nh->nh_prev == nh);

  if (nh->nh_next)
    nh->nh_next->nh_prev = nh->nh_prev;
  else
    nua->nua_handles_tail = nh->nh_prev;

  *nh->nh_prev = nh->nh_next;

  nh->nh_prev = NULL;
  nh->nh_next = NULL;
}


void nh_destroy(nua_t *nua, nua_handle_t *nh)
{
  assert(nh); assert(nh != nua->nua_dhandle);

  nh_enter;

  if (nh->nh_notifier)
    nea_server_destroy(nh->nh_notifier), nh->nh_notifier = NULL;

  nua_creq_deinit(nh->nh_cr, NULL);
  if (nh->nh_ss)
    nua_creq_deinit(nh->nh_ss->ss_crequest, NULL);

  if (nh->nh_ds->ds_leg) {
    nta_leg_destroy(nh->nh_ds->ds_leg), nh->nh_ds->ds_leg = NULL;
  }

  if (nh->nh_ss->ss_srequest->sr_irq) {
    nta_incoming_destroy(nh->nh_ss->ss_srequest->sr_irq);
    nh->nh_ss->ss_srequest->sr_irq = NULL;
  }

  if (nh->nh_soa)
    soa_destroy(nh->nh_soa), nh->nh_soa = NULL;

  if (nh_is_inserted(nh))
    nh_remove(nua, nh);

  nua_handle_unref(nh);		/* Remove stack reference */
}

void nua_creq_deinit(struct nua_client_request *cr, nta_outgoing_t *orq)
{
  if (orq == NULL || orq == cr->cr_orq) {
    cr->cr_retry_count = 0;
    cr->cr_offer_sent = cr->cr_answer_recv = 0;

    if (cr->cr_msg)
      msg_destroy(cr->cr_msg);
    cr->cr_msg = NULL;

    if (cr->cr_orq)
      nta_outgoing_destroy(cr->cr_orq);
    cr->cr_orq = NULL;
  }
  else {
    nta_outgoing_destroy(orq);
  }
}

/* ======================================================================== */

/**@internal
 * Initialize handle Allow and authentication info.
 *
 * @retval -1 upon an error
 * @retval 0 when successful
 */
int nua_stack_init_handle(nua_t *nua, nua_handle_t *nh,
			  enum nh_kind kind,
			  char const *default_allow,
			  tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  int retval = 0;

  if (nh == NULL)
    return -1;

  if (kind && !nh_is_special(nh) && !nh->nh_has_invite) {
    switch (kind) {
    case nh_has_invite:    nh->nh_has_invite = 1;    break;
    case nh_has_subscribe: nh->nh_has_subscribe = 1; break;
    case nh_has_notify:    nh->nh_has_notify = 1;    break;
    case nh_has_register:  nh->nh_has_register = 1;  break;
    case nh_has_streaming: nh->nh_has_streaming = 1; break;
    case nh_has_nothing:
    default:
      break;
    }
  }

  assert(nh != nua->nua_dhandle);

  ta_start(ta, tag, value);

  if (nua_stack_set_params(nua, nh, nua_i_error, ta_args(ta)) < 0)
    retval = -1;

  if (!retval && !nh->nh_soa && nua->nua_dhandle->nh_soa) {
    nh->nh_soa = soa_clone(nua->nua_dhandle->nh_soa, nua->nua_root, nh);

    if (nh->nh_soa && nh->nh_tags)
      if (soa_set_params(nh->nh_soa, TAG_NEXT(nh->nh_tags)))
	retval = -1;
  }

  if (!retval && nh->nh_soa)
    if (soa_set_params(nh->nh_soa, ta_tags(ta)) < 0)
      retval = -1;

  ta_end(ta);

  if (retval || nh->nh_init) /* Already initialized? */
    return retval;

#if HAVE_UICC_H
  if (nh->nh_has_register && nua->nua_uicc)
    auc_with_uicc(&nh->nh_auth, nh->nh_home, nua->nua_uicc);
#endif

  if (nh->nh_tags)
    nh_authorize(nh, TAG_NEXT(nh->nh_tags));

  nh->nh_ss->ss_min_se = NH_PGET(nh, min_se);
  nh->nh_ss->ss_session_timer = NH_PGET(nh, session_timer);
  nh->nh_ss->ss_refresher = NH_PGET(nh, refresher);

  nh->nh_init = 1;

  return 0;
}

/** @internal Create a handle for processing incoming request */
nua_handle_t *nua_stack_incoming_handle(nua_t *nua,
					nta_incoming_t *irq,
					sip_t const *sip,
					enum nh_kind kind,
					int create_dialog)
{
  nua_handle_t *nh;
  url_t const *url;
  char const *default_allow = NULL; /* XXX - should be argument? */
  sip_to_t to[1];
  sip_from_t from[1];

  assert(sip && sip->sip_from && sip->sip_to);

  if (sip->sip_contact)
    url = sip->sip_contact->m_url;
  else
    url = sip->sip_from->a_url;

  sip_from_init(from)->a_display = sip->sip_to->a_display;
  *from->a_url = *sip->sip_to->a_url;

  sip_to_init(to)->a_display = sip->sip_from->a_display;
  *to->a_url = *sip->sip_from->a_url;

  nh = nh_create(nua,
		 NUTAG_URL((url_string_t *)url),
		 SIPTAG_TO(to), /* Local address */
		 SIPTAG_FROM(from), /* Remote address */
		 TAG_END());

  if (nua_stack_init_handle(nh->nh_nua, nh, kind, default_allow,
			    TAG_END()) < 0)
    nh_destroy(nua, nh), nh = NULL;

  if (nh && create_dialog) {
    struct nua_dialog_state *ds = nh->nh_ds;

    nua_dialog_store_peer_info(nh, ds, sip);

    ds->ds_leg = nta_leg_tcreate(nua->nua_nta, nua_stack_process_request, nh,
				 SIPTAG_CALL_ID(sip->sip_call_id),
				 SIPTAG_FROM(sip->sip_to),
				 SIPTAG_TO(sip->sip_from),
				 NTATAG_REMOTE_CSEQ(sip->sip_cseq->cs_seq),
				 TAG_END());

    if (!ds->ds_leg || !nta_leg_tag(ds->ds_leg, nta_incoming_tag(irq, NULL)))
      nh_destroy(nua, nh), nh = NULL;
  }

  if (nh)
    nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);

  return nh;
}


/** @internal Add authorization data */
int nh_authorize(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...)
{
  int retval = 0;
  tagi_t const *ti;
  ta_list ta;

  ta_start(ta, tag, value);

  for (ti = ta_args(ta); ti; ti = tl_next(ti)) {
    if (ti->t_tag == nutag_auth && ti->t_value) {
      char *data = (char *)ti->t_value;
      int rv = auc_credentials(&nh->nh_auth, nh->nh_home, data);

      if (rv > 0) {
	retval = 1;
      }
      else if (rv < 0) {
	retval = -1;
	break;
      }
    }
  }

  ta_end(ta);

  return retval;
}

/**@internal
 * Collect challenges from response.
 *
 * @return Number of updated challenges, 0 if no updates found.
 * @retval -1 upon error.
 */
static
int nh_challenge(nua_handle_t *nh, sip_t const *sip)
{
  int server = 0, proxy = 0;

  if (sip->sip_www_authenticate)
    server = auc_challenge(&nh->nh_auth, nh->nh_home,
			   sip->sip_www_authenticate,
			   sip_authorization_class);

  if (sip->sip_proxy_authenticate)
    proxy = auc_challenge(&nh->nh_auth, nh->nh_home,
			  sip->sip_proxy_authenticate,
			  sip_proxy_authorization_class);

  if (server < 0 || proxy < 0)
    return -1;

  return server + proxy;
}

/**@internal
 * Create a request message.
 *
 * @param nua
 * @param nh
 * @param cr
 * @param restart
 * @param method
 * @param name
 * @param tag, value, ... list of tag-value pairs
 */
msg_t *nua_creq_msg(nua_t *nua,
		    nua_handle_t *nh,
		    struct nua_client_request *cr,
		    int restart,
		    sip_method_t method, char const *name,
		    tag_type_t tag, tag_value_t value, ...)
{
  struct nua_dialog_state *ds = nh->nh_ds;
  msg_t *msg;
  sip_t *sip;
  ta_list ta;
  url_string_t const *url = NULL;
  long seq = -1;
  int copy = 1, use_dialog = 0, add_contact = 0, add_service_route;

  /* If restarting, use existing message */
  if (restart) {
    msg = cr->cr_msg; sip = sip_object(msg);

    /* Trying to restart different method? */
    if (sip && method && sip->sip_request->rq_method != method) {
      SU_DEBUG_3(("nua(%p): trying to %s "
		  "but there is already %s waiting to restart\n",
		  nh, name, sip->sip_request->rq_method_name));
      restart = 0, msg = NULL; sip = NULL;
    }

    /* Remove CSeq */
    if (sip && sip->sip_cseq)
      sip_header_remove(msg, sip, (sip_header_t *)sip->sip_cseq);
    if (sip && sip->sip_request)
      method = sip->sip_request->rq_method,
	name = sip->sip_request->rq_method_name;
  }

  if (!restart) {
    if (cr->cr_msg) {
      /* If method is ACK or CANCEL, use existing CSeq */
      if (method == sip_method_ack || method == sip_method_cancel) {
	sip_t *nh_sip = sip_object(cr->cr_msg);
	if (nh_sip && nh_sip->sip_cseq)
	  seq = nh_sip->sip_cseq->cs_seq;
	/* ACK/CANCEL cannot be restarted so we do not copy message */
	copy = 0;
      }
      else
	msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
    }
    msg = nta_msg_create(nua->nua_nta, 0);
    tl_gets(nh->nh_tags, NUTAG_URL_REF(url), TAG_END());
    sip_add_tl(msg, sip_object(msg), TAG_NEXT(nh->nh_tags));
  }

  ta_start(ta, tag, value);

  sip = sip_object(msg);
  if (!sip)
    goto error;

  {
    tl_gets(ta_args(ta),
	    NUTAG_URL_REF(url),
	    NUTAG_USE_DIALOG_REF(use_dialog),
	    /* NUTAG_COPY_REF(copy), */
	    NUTAG_ADD_CONTACT_REF(add_contact),
	    TAG_END());

    if (method == sip_method_register && url == NULL && !sip->sip_request) {
      tl_gets(ta_args(ta), NUTAG_REGISTRAR_REF(url), TAG_END());
      if (url == NULL)
	tl_gets(nh->nh_tags, NUTAG_REGISTRAR_REF(url), TAG_END());
      if (url == NULL)
	url = (url_string_t *)nua->nua_registrar;
    }

    if (seq != -1) {
      sip_cseq_t *cseq;
     
      assert(method != sip_method_unknown || name || sip->sip_request);
      
      if (method || name)
	cseq = sip_cseq_create(msg_home(msg), seq, method, name);
      else 
	cseq = sip_cseq_create(msg_home(msg), seq, 
			       sip->sip_request->rq_method, 
			       sip->sip_request->rq_method_name);

      sip_header_insert(msg, sip, (sip_header_t *)cseq);
    }

    if (ds->ds_leg) {
      add_service_route = 0;

      /* If leg has established route, use it, not original URL */
      if (ds->ds_route)
	url = NULL;

      if (sip_add_tl(msg, sip, ta_tags(ta)) < 0 ||
	  nta_msg_request_complete(msg, ds->ds_leg, method, name, url) < 0)
	goto error;
    }
    else {
      nta_leg_t *leg = nua->nua_dhandle->nh_ds->ds_leg;

      if (sip_add_tl(msg, sip, ta_tags(ta)) < 0
	  || (ds->ds_remote_tag &&
	      sip_to_tag(nh->nh_home, sip->sip_to, ds->ds_remote_tag) < 0)
	  || (sip->sip_from == NULL &&<commit_msg>nua_stack.c: do not use empty tag parameter with To header.<commit_after>/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: <NAME> <<EMAIL>>
 *
 * This library is free software; you can redistribute it and/or
 * 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
 *
 */

/**@CFILE nua_stack.c
 * @brief Sofia-SIP User Agent Engine implementation
 *
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 * @author <NAME> <<EMAIL>>
 *
 * @date Created: Wed Feb 14 18:32:58 2001 ppessi
 */

#include "config.h"

#include <sofia-sip/su_tag_class.h>
#include <sofia-sip/su_tag_class.h>
#include <sofia-sip/su_tagarg.h>
#include <sofia-sip/su_strlst.h>
#include <sofia-sip/su_uniqueid.h>

#include <sofia-sip/su_tag_io.h>

#define SU_ROOT_MAGIC_T   struct nua_s
#define SU_MSG_ARG_T      struct event_s

#define NUA_SAVED_EVENT_T su_msg_t *

#define NTA_AGENT_MAGIC_T    struct nua_s
#define NTA_LEG_MAGIC_T      struct nua_handle_s
#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
#define NTA_INCOMING_MAGIC_T struct nua_handle_s

#include <sofia-sip/sip.h>
#include <sofia-sip/sip_header.h>
#include <sofia-sip/sip_status.h>
#include <sofia-sip/sip_util.h>

#include <sofia-sip/tport_tag.h>
#include <sofia-sip/nta.h>
#include <sofia-sip/nta_tport.h>
#include <sofia-sip/auth_client.h>

#include <sofia-sip/soa.h>

#include "sofia-sip/nua.h"
#include "sofia-sip/nua_tag.h"
#include "nua_stack.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>

#include <assert.h>

/* ========================================================================
 *
 *                       Protocol stack side
 *
 * ======================================================================== */

nua_handle_t *nh_create(nua_t *nua, tag_type_t t, tag_value_t v, ...);
static void nh_append(nua_t *nua, nua_handle_t *nh);
static void nh_remove(nua_t *nua, nua_handle_t *nh);

static int nh_authorize(nua_handle_t *nh,
			tag_type_t tag, tag_value_t value, ...);

static int nh_challenge(nua_handle_t *nh, sip_t const *sip);

static void nua_stack_timer(nua_t *nua, su_timer_t *t, su_timer_arg_t *a);

/* ---------------------------------------------------------------------- */
/* Constant data */

/**@internal Default internal error. */
char const nua_internal_error[] = "Internal NUA Error";

char const nua_application_sdp[] = "application/sdp";

#define NUA_STACK_TIMER_INTERVAL (1000)

/* ----------------------------------------------------------------------
 * Initialization & deinitialization
 */

int nua_stack_init(su_root_t *root, nua_t *nua)
{
  su_home_t *home;

  nua_handle_t *dnh;
  int media_enable = 1;
  soa_session_t *soa = NULL;
  char const *soa_name = NULL;

  static int initialized_logs = 0;

  enter;

  if (!initialized_logs) {
    extern su_log_t tport_log[];
    extern su_log_t nta_log[];
    extern su_log_t nea_log[];
    extern su_log_t iptsec_log[];

    su_log_init(tport_log);
    su_log_init(nta_log);
    su_log_init(nea_log);
    su_log_init(iptsec_log);

    initialized_logs = 1;
  }

  nua->nua_root = root;

  home = nua->nua_home;
  nua->nua_handles_tail = &nua->nua_handles;
  sip_from_init(nua->nua_from);

  dnh = su_home_clone(nua->nua_home, sizeof (*dnh) + sizeof(*dnh->nh_prefs));
  if (!dnh)
    return -1;

  dnh->nh_prefs = (void *)(dnh + 1);
  dnh->nh_valid = nua_handle;
  dnh->nh_nua = nua;
  nua_handle_ref(dnh); dnh->nh_ref_by_stack = 1; 
  nua_handle_ref(dnh); dnh->nh_ref_by_user = 1;
  nh_append(nua, dnh);
  dnh->nh_ds->ds_local = nua->nua_from;
  dnh->nh_ds->ds_remote = nua->nua_from;

  if (nua_stack_set_defaults(dnh, dnh->nh_prefs) < 0)
    return -1;

  if (nua_stack_init_instance(dnh, nua->nua_args) < 0)
    return -1;

  nua->nua_invite_accept = sip_accept_make(home, SDP_MIME_TYPE);

  nua->nua_nta = nta_agent_create(root, NONE, NULL, NULL,
				  NTATAG_MERGE_482(1),
				  NTATAG_CLIENT_RPORT(1),
				  NTATAG_UA(1),
#if HAVE_SOFIA_SMIME
				  NTATAG_SMIME(nua->sm),
#endif
				  TPTAG_STUN_SERVER(1),
				  TAG_NEXT(nua->nua_args));

  dnh->nh_ds->ds_leg = nta_leg_tcreate(nua->nua_nta,
				       nua_stack_process_request, dnh,
				       NTATAG_NO_DIALOG(1),
				       TAG_END());

  if (nua->nua_nta == NULL ||
      dnh->nh_ds->ds_leg == NULL || 
      nta_agent_set_params(nua->nua_nta, NTATAG_UA(1), TAG_END()) < 0 ||
      nua_stack_init_transport(nua, nua->nua_args) < 0) {
    SU_DEBUG_1(("nua: initializing SIP stack failed\n"));
  }

  if (nua_stack_set_from(nua, 1, nua->nua_args) < 0)
    return -1;

  /* Set initial nta/soa parameters */
  if (tl_gets(nua->nua_args,
	      NUTAG_MEDIA_ENABLE_REF(media_enable),
	      NUTAG_SOA_NAME_REF(soa_name),
	      TAG_NULL()) < 0)
    return -1;

  nua->nua_media_enable = media_enable;
  
  if (media_enable) {
    if (soa == NULL)
      soa = soa_create(soa_name, nua->nua_root, nua->nua_dhandle);
    dnh->nh_soa = soa;
    soa_set_params(soa, TAG_NEXT(nua->nua_args));
  }

  nua->nua_timer = su_timer_create(su_root_task(root),
				   NUA_STACK_TIMER_INTERVAL);

  if (!nua->nua_timer)
    return -1;

  nua_stack_timer(nua, nua->nua_timer, NULL);

  nua->nua_args = NULL;

  return 0;
}

void nua_stack_deinit(su_root_t *root, nua_t *nua)
{
  enter;

  su_timer_destroy(nua->nua_timer), nua->nua_timer = NULL;
  nta_agent_destroy(nua->nua_nta), nua->nua_nta = NULL;
}

/* ----------------------------------------------------------------------
 * Sending events to client application
 */

static void nua_stack_shutdown(nua_t *);

void
  nua_stack_authenticate(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_respond(nua_t *, nua_handle_t *, int , char const *, tagi_t const *),
  nua_stack_destroy_handle(nua_t *, nua_handle_t *, tagi_t const *);

/* Notifier */
void
  nua_stack_authorize(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_notifier(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *),
  nua_stack_terminate(nua_t *, nua_handle_t *, nua_event_t, tagi_t const *);

int nh_notifier_shutdown(nua_handle_t *nh, nea_event_t *ev,
			 tag_type_t t, tag_value_t v, ...);

/** @internal Send an event to the application. */
int nua_stack_event(nua_t *nua, nua_handle_t *nh, msg_t *msg,
		    nua_event_t event, int status, char const *phrase,
		    tag_type_t tag, tag_value_t value, ...)
{
  su_msg_r sumsg = SU_MSG_R_INIT;

  ta_list ta;
  int e_len, len, xtra, p_len;

  enter;

  if (nua_log->log_level >= 5) {
    char const *name = nua_event_name(event) + 4;
    char const *p = phrase ? phrase : "";

    if (status == 0)
      SU_DEBUG_5(("nua(%p): %s %s\n", nh, name, p));
    else
      SU_DEBUG_5(("nua(%p): %s %u %s\n", nh, name, status, p));
  }

  if (event == nua_r_destroy) {
    if (msg)
      msg_destroy(msg);
    if (status >= 200) {
      nh_destroy(nua, nh);
    }
    return event;
  }

  if (event > nua_r_method || (nh && !nh->nh_valid) ||
      (nua->nua_shutdown && event != nua_r_shutdown)) {
    if (msg)
      msg_destroy(msg);
    return event;
  }

  ta_start(ta, tag, value);

  e_len = offsetof(event_t, e_tags);
  len = tl_len(ta_args(ta));
  xtra = tl_xtra(ta_args(ta), len);
  p_len = phrase ? strlen(phrase) + 1 : 1;

  if (su_msg_create(sumsg, nua->nua_client, nua->nua_server,
		    nua_event, e_len + len + xtra + p_len) == 0) {
    event_t *e = su_msg_data(sumsg);

    tagi_t *t = e->e_tags, *t_end = (tagi_t *)((char *)t + len);
    void *b = t_end, *end = (char *)b + xtra;

    t = tl_dup(t, ta_args(ta), &b);
    assert(t == t_end); assert(b == end);

    e->e_event = event;
    e->e_nh = nh ? nua_handle_ref(nh) : nua->nua_dhandle;
    e->e_status = status;
    e->e_phrase = strcpy(end, phrase ? phrase : "");
    e->e_msg = msg;

    if (su_msg_send(sumsg) != 0)
      nua_handle_unref(nh);
  }

  ta_end(ta);

  return event;
}

/* ----------------------------------------------------------------------
 * Post signal to stack itself
 */
void nua_stack_post_signal(nua_handle_t *nh, nua_event_t event,
			   tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  ta_start(ta, tag, value);
  nua_signal((nh)->nh_nua, nh, NULL, 1, event, 0, NULL, ta_tags(ta));
  ta_end(ta);
}


/* ----------------------------------------------------------------------
 * Receiving events from client
 */
void nua_stack_signal(nua_t *nua, su_msg_r msg, nua_event_data_t *e)
{
  nua_handle_t *nh = e->e_nh;
  tagi_t *tags = e->e_tags;

  assert(tags);

  if (nh) {
    if (!nh->nh_prev)
      nh_append(nua, nh);
    if (!nh->nh_ref_by_stack) {
      nh->nh_ref_by_stack = 1;
      nua_handle_ref(nh);
    }
  }

  if (nua_log->log_level >= 5) {
    char const *name = nua_event_name(e->e_event);
    if (e->e_status == 0)
      SU_DEBUG_5(("nua(%p): signal %s\n", nh, name + 4));
    else
      SU_DEBUG_5(("nua(%p): signal %s %u %s\n",
		  nh, name + 4, e->e_status, e->e_phrase ? e->e_phrase : ""));
  }

  su_msg_save(nua->nua_signal, msg);

  if (nua->nua_shutdown && !e->e_always) {
    /* Shutting down */
    nua_stack_event(nua, nh, NULL, e->e_event,
		    901, "Stack is going down",
		    TAG_END());
  }
  else switch (e->e_event) {
  case nua_r_get_params:
    nua_stack_get_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
    break;
  case nua_r_set_params:
    nua_stack_set_params(nua, nh ? nh : nua->nua_dhandle, e->e_event, tags);
    break;
  case nua_r_shutdown:
    nua_stack_shutdown(nua);
    break;
  case nua_r_register:
  case nua_r_unregister:
    nua_stack_register(nua, nh, e->e_event, tags);
    break;
  case nua_r_invite:
    nua_stack_invite(nua, nh, e->e_event, tags);
    break;
  case nua_r_cancel:
    nua_stack_cancel(nua, nh, e->e_event, tags);
    break;
  case nua_r_bye:
    nua_stack_bye(nua, nh, e->e_event, tags);
    break;
  case nua_r_options:
    nua_stack_options(nua, nh, e->e_event, tags);
    break;
  case nua_r_refer:
    nua_stack_refer(nua, nh, e->e_event, tags);
    break;
  case nua_r_publish:
  case nua_r_unpublish:
    nua_stack_publish(nua, nh, e->e_event, tags);
    break;
  case nua_r_info:
    nua_stack_info(nua, nh, e->e_event, tags);
    break;
  case nua_r_update:
    nua_stack_update(nua, nh, e->e_event, tags);
    break;
  case nua_r_message:
    nua_stack_message(nua, nh, e->e_event, tags);
    break;
  case nua_r_subscribe:
  case nua_r_unsubscribe:
    nua_stack_subscribe(nua, nh, e->e_event, tags);
    break;
  case nua_r_notify:
    nua_stack_notify(nua, nh, e->e_event, tags);
    break;
  case nua_r_notifier:
    nua_stack_notifier(nua, nh, e->e_event, tags);
    break;
  case nua_r_terminate:
    nua_stack_terminate(nua, nh, e->e_event, tags);
    break;
  case nua_r_method:
    nua_stack_method(nua, nh, e->e_event, tags);
    break;
  case nua_r_authenticate:
    nua_stack_authenticate(nua, nh, e->e_event, tags);
    break;
  case nua_r_authorize:
    nua_stack_authorize(nua, nh, e->e_event, tags);
    break;
  case nua_r_ack:
    nua_stack_ack(nua, nh, e->e_event, tags);
    break;
  case nua_r_respond:
    nua_stack_respond(nua, nh, e->e_status, e->e_phrase, tags);
    break;
  case nua_r_destroy:
    nua_stack_destroy_handle(nua, nh, tags);
    break;
  default:
    break;
  }

  if (su_msg_is_non_null(nua->nua_signal))
    su_msg_destroy(nua->nua_signal);

  if (nh != nua->nua_dhandle)
    nua_handle_unref(nh);
}

/* ====================================================================== */

static int nh_call_pending(nua_handle_t *nh, sip_time_t time);

/**@internal
 * Timer routine.
 *
 * Go through all active handles and execute pending tasks
 */
void nua_stack_timer(nua_t *nua, su_timer_t *t, su_timer_arg_t *a)
{
  nua_handle_t *nh, *nh_next;
  sip_time_t now = sip_now();
  su_root_t *root = su_timer_root(t);

  su_timer_set(t, nua_stack_timer, a);

  if (nua->nua_shutdown) {
    nua_stack_shutdown(nua);
    return;
  }

  for (nh = nua->nua_handles; nh; nh = nh_next) {
    nh_next = nh->nh_next;
    nh_call_pending(nh, now);
    su_root_yield(root);	/* Handle received packets */
  }
}


static
int nh_call_pending(nua_handle_t *nh, sip_time_t now)
{
  nua_dialog_usage_t *du;
  sip_time_t next = now + NUA_STACK_TIMER_INTERVAL / 1000;

  for (du = nh->nh_ds->ds_usage; du; du = du->du_next) {
    if (now == 0)
      break;
    if (du->du_refresh && du->du_refresh < next)
      break;
  }

  if (du == NULL)
    return 0;

  nua_handle_ref(nh);

  while (du) {
    nua_dialog_usage_t *du_next = du->du_next;

    nua_dialog_usage_refresh(nh, du, now);

    if (du_next == NULL)
      break;

    for (du = nh->nh_ds->ds_usage; du; du = du->du_next)
      if (du == du_next)
	break;

    for (; du; du = du->du_next) {
      if (now == 0)
	break;
      if (du->du_refresh && du->du_refresh < next)
	break;
    }
  }

  nua_handle_unref(nh);

  return 1;
}


/* ====================================================================== */

/** @internal Shut down stack. */
void nua_stack_shutdown(nua_t *nua)
{
  nua_handle_t *nh, *nh_next;
  int busy = 0;
  sip_time_t now = sip_now();
  int status;
  char const *phrase;
  struct nua_session_state *ss;

  enter;

  if (!nua->nua_shutdown)
    nua->nua_shutdown = now;

  for (nh = nua->nua_handles; nh; nh = nh_next) {
    nh_next = nh->nh_next;

    ss = nh->nh_ss;

    if (ss->ss_srequest->sr_respond) {
      ss->ss_srequest->sr_respond(nua, nh, SIP_410_GONE, NULL);
      busy++;
    }

    busy += nh_call_pending(nh, 0);

    if (nh->nh_soa) {
      soa_destroy(nh->nh_soa), nh->nh_soa = NULL;
    }

    if (nh->nh_cr->cr_orq || nh->nh_ss->ss_crequest->cr_orq)
      busy++;

    if (nh_notifier_shutdown(nh, NULL, NEATAG_REASON("noresource"), TAG_END()))
      busy++;
  }

  if (!busy)
    SET_STATUS(200, "Shutdown successful");
  else if (now == nua->nua_shutdown)
    SET_STATUS(100, "Shutdown started");
  else if (now - nua->nua_shutdown < 30)
    SET_STATUS(101, "Shutdown in progress");
  else
    SET_STATUS(500, "Shutdown timeout");

  if (status >= 200) {
    for (nh = nua->nua_handles; nh; nh = nh_next) {
      nh_next = nh->nh_next;
      while (nh->nh_ds && nh->nh_ds->ds_usage) {
	nua_dialog_usage_remove(nh, nh->nh_ds, nh->nh_ds->ds_usage);
      }
    }
    su_timer_destroy(nua->nua_timer), nua->nua_timer = NULL;
    nta_agent_destroy(nua->nua_nta), nua->nua_nta = NULL;
  }

  nua_stack_event(nua, NULL, NULL, nua_r_shutdown, status, phrase, TAG_END());
}

/* ---------------------------------------------------------------------- */

/** @internal Create a handle */
nua_handle_t *nh_create(nua_t *nua, tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  nua_handle_t *nh;

  enter;

  ta_start(ta, tag, value);
  nh = nh_create_handle(nua, NULL, ta_args(ta));
  ta_end(ta);

  if (nh) {
    nh->nh_ref_by_stack = 1;
    nh_append(nua, nh);
  }

  return nh;
}

/** @internal Append an handle to the list of handles */
void nh_append(nua_t *nua, nua_handle_t *nh)
{
  nh->nh_next = NULL;
  nh->nh_prev = nua->nua_handles_tail;
  *nua->nua_handles_tail = nh;
  nua->nua_handles_tail = &nh->nh_next;
}

nua_handle_t *nh_validate(nua_t *nua, nua_handle_t *maybe)
{
  nua_handle_t *nh;

  if (maybe)
    for (nh = nua->nua_handles; nh; nh = nh->nh_next)
      if (nh == maybe)
	return nh;

  return NULL;
}

void nua_stack_destroy_handle(nua_t *nua, nua_handle_t *nh, tagi_t const *tags)
{
  nh_call_pending(nh, 0);	/* Call pending operations with 0 */

  if (nh->nh_notifier)
    nua_stack_terminate(nua, nh, 0, NULL);

#if 0
  if (nh->nh_ref_by_user) {
    nh->nh_ref_by_user = 0;
    nua_handle_unref(nh);
  }
#endif

  nh_destroy(nua, nh);
}

#define nh_is_inserted(nh) ((nh)->nh_prev != NULL)

/** @internal Remove a handle from list of handles */
static
void nh_remove(nua_t *nua, nua_handle_t *nh)
{
  assert(nh_is_inserted(nh)); assert(*nh->nh_prev == nh);

  if (nh->nh_next)
    nh->nh_next->nh_prev = nh->nh_prev;
  else
    nua->nua_handles_tail = nh->nh_prev;

  *nh->nh_prev = nh->nh_next;

  nh->nh_prev = NULL;
  nh->nh_next = NULL;
}


void nh_destroy(nua_t *nua, nua_handle_t *nh)
{
  assert(nh); assert(nh != nua->nua_dhandle);

  nh_enter;

  if (nh->nh_notifier)
    nea_server_destroy(nh->nh_notifier), nh->nh_notifier = NULL;

  nua_creq_deinit(nh->nh_cr, NULL);
  if (nh->nh_ss)
    nua_creq_deinit(nh->nh_ss->ss_crequest, NULL);

  if (nh->nh_ds->ds_leg) {
    nta_leg_destroy(nh->nh_ds->ds_leg), nh->nh_ds->ds_leg = NULL;
  }

  if (nh->nh_ss->ss_srequest->sr_irq) {
    nta_incoming_destroy(nh->nh_ss->ss_srequest->sr_irq);
    nh->nh_ss->ss_srequest->sr_irq = NULL;
  }

  if (nh->nh_soa)
    soa_destroy(nh->nh_soa), nh->nh_soa = NULL;

  if (nh_is_inserted(nh))
    nh_remove(nua, nh);

  nua_handle_unref(nh);		/* Remove stack reference */
}

void nua_creq_deinit(struct nua_client_request *cr, nta_outgoing_t *orq)
{
  if (orq == NULL || orq == cr->cr_orq) {
    cr->cr_retry_count = 0;
    cr->cr_offer_sent = cr->cr_answer_recv = 0;

    if (cr->cr_msg)
      msg_destroy(cr->cr_msg);
    cr->cr_msg = NULL;

    if (cr->cr_orq)
      nta_outgoing_destroy(cr->cr_orq);
    cr->cr_orq = NULL;
  }
  else {
    nta_outgoing_destroy(orq);
  }
}

/* ======================================================================== */

/**@internal
 * Initialize handle Allow and authentication info.
 *
 * @retval -1 upon an error
 * @retval 0 when successful
 */
int nua_stack_init_handle(nua_t *nua, nua_handle_t *nh,
			  enum nh_kind kind,
			  char const *default_allow,
			  tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  int retval = 0;

  if (nh == NULL)
    return -1;

  if (kind && !nh_is_special(nh) && !nh->nh_has_invite) {
    switch (kind) {
    case nh_has_invite:    nh->nh_has_invite = 1;    break;
    case nh_has_subscribe: nh->nh_has_subscribe = 1; break;
    case nh_has_notify:    nh->nh_has_notify = 1;    break;
    case nh_has_register:  nh->nh_has_register = 1;  break;
    case nh_has_streaming: nh->nh_has_streaming = 1; break;
    case nh_has_nothing:
    default:
      break;
    }
  }

  assert(nh != nua->nua_dhandle);

  ta_start(ta, tag, value);

  if (nua_stack_set_params(nua, nh, nua_i_error, ta_args(ta)) < 0)
    retval = -1;

  if (!retval && !nh->nh_soa && nua->nua_dhandle->nh_soa) {
    nh->nh_soa = soa_clone(nua->nua_dhandle->nh_soa, nua->nua_root, nh);

    if (nh->nh_soa && nh->nh_tags)
      if (soa_set_params(nh->nh_soa, TAG_NEXT(nh->nh_tags)))
	retval = -1;
  }

  if (!retval && nh->nh_soa)
    if (soa_set_params(nh->nh_soa, ta_tags(ta)) < 0)
      retval = -1;

  ta_end(ta);

  if (retval || nh->nh_init) /* Already initialized? */
    return retval;

#if HAVE_UICC_H
  if (nh->nh_has_register && nua->nua_uicc)
    auc_with_uicc(&nh->nh_auth, nh->nh_home, nua->nua_uicc);
#endif

  if (nh->nh_tags)
    nh_authorize(nh, TAG_NEXT(nh->nh_tags));

  nh->nh_ss->ss_min_se = NH_PGET(nh, min_se);
  nh->nh_ss->ss_session_timer = NH_PGET(nh, session_timer);
  nh->nh_ss->ss_refresher = NH_PGET(nh, refresher);

  nh->nh_init = 1;

  return 0;
}

/** @internal Create a handle for processing incoming request */
nua_handle_t *nua_stack_incoming_handle(nua_t *nua,
					nta_incoming_t *irq,
					sip_t const *sip,
					enum nh_kind kind,
					int create_dialog)
{
  nua_handle_t *nh;
  url_t const *url;
  char const *default_allow = NULL; /* XXX - should be argument? */
  sip_to_t to[1];
  sip_from_t from[1];

  assert(sip && sip->sip_from && sip->sip_to);

  if (sip->sip_contact)
    url = sip->sip_contact->m_url;
  else
    url = sip->sip_from->a_url;

  sip_from_init(from)->a_display = sip->sip_to->a_display;
  *from->a_url = *sip->sip_to->a_url;

  sip_to_init(to)->a_display = sip->sip_from->a_display;
  *to->a_url = *sip->sip_from->a_url;

  nh = nh_create(nua,
		 NUTAG_URL((url_string_t *)url),
		 SIPTAG_TO(to), /* Local address */
		 SIPTAG_FROM(from), /* Remote address */
		 TAG_END());

  if (nua_stack_init_handle(nh->nh_nua, nh, kind, default_allow,
			    TAG_END()) < 0)
    nh_destroy(nua, nh), nh = NULL;

  if (nh && create_dialog) {
    struct nua_dialog_state *ds = nh->nh_ds;

    nua_dialog_store_peer_info(nh, ds, sip);

    ds->ds_leg = nta_leg_tcreate(nua->nua_nta, nua_stack_process_request, nh,
				 SIPTAG_CALL_ID(sip->sip_call_id),
				 SIPTAG_FROM(sip->sip_to),
				 SIPTAG_TO(sip->sip_from),
				 NTATAG_REMOTE_CSEQ(sip->sip_cseq->cs_seq),
				 TAG_END());

    if (!ds->ds_leg || !nta_leg_tag(ds->ds_leg, nta_incoming_tag(irq, NULL)))
      nh_destroy(nua, nh), nh = NULL;
  }

  if (nh)
    nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);

  return nh;
}


/** @internal Add authorization data */
int nh_authorize(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...)
{
  int retval = 0;
  tagi_t const *ti;
  ta_list ta;

  ta_start(ta, tag, value);

  for (ti = ta_args(ta); ti; ti = tl_next(ti)) {
    if (ti->t_tag == nutag_auth && ti->t_value) {
      char *data = (char *)ti->t_value;
      int rv = auc_credentials(&nh->nh_auth, nh->nh_home, data);

      if (rv > 0) {
	retval = 1;
      }
      else if (rv < 0) {
	retval = -1;
	break;
      }
    }
  }

  ta_end(ta);

  return retval;
}

/**@internal
 * Collect challenges from response.
 *
 * @return Number of updated challenges, 0 if no updates found.
 * @retval -1 upon error.
 */
static
int nh_challenge(nua_handle_t *nh, sip_t const *sip)
{
  int server = 0, proxy = 0;

  if (sip->sip_www_authenticate)
    server = auc_challenge(&nh->nh_auth, nh->nh_home,
			   sip->sip_www_authenticate,
			   sip_authorization_class);

  if (sip->sip_proxy_authenticate)
    proxy = auc_challenge(&nh->nh_auth, nh->nh_home,
			  sip->sip_proxy_authenticate,
			  sip_proxy_authorization_class);

  if (server < 0 || proxy < 0)
    return -1;

  return server + proxy;
}

/**@internal
 * Create a request message.
 *
 * @param nua
 * @param nh
 * @param cr
 * @param restart
 * @param method
 * @param name
 * @param tag, value, ... list of tag-value pairs
 */
msg_t *nua_creq_msg(nua_t *nua,
		    nua_handle_t *nh,
		    struct nua_client_request *cr,
		    int restart,
		    sip_method_t method, char const *name,
		    tag_type_t tag, tag_value_t value, ...)
{
  struct nua_dialog_state *ds = nh->nh_ds;
  msg_t *msg;
  sip_t *sip;
  ta_list ta;
  url_string_t const *url = NULL;
  long seq = -1;
  int copy = 1, use_dialog = 0, add_contact = 0, add_service_route;

  /* If restarting, use existing message */
  if (restart) {
    msg = cr->cr_msg; sip = sip_object(msg);

    /* Trying to restart different method? */
    if (sip && method && sip->sip_request->rq_method != method) {
      SU_DEBUG_3(("nua(%p): trying to %s "
		  "but there is already %s waiting to restart\n",
		  nh, name, sip->sip_request->rq_method_name));
      restart = 0, msg = NULL; sip = NULL;
    }

    /* Remove CSeq */
    if (sip && sip->sip_cseq)
      sip_header_remove(msg, sip, (sip_header_t *)sip->sip_cseq);
    if (sip && sip->sip_request)
      method = sip->sip_request->rq_method,
	name = sip->sip_request->rq_method_name;
  }

  if (!restart) {
    if (cr->cr_msg) {
      /* If method is ACK or CANCEL, use existing CSeq */
      if (method == sip_method_ack || method == sip_method_cancel) {
	sip_t *nh_sip = sip_object(cr->cr_msg);
	if (nh_sip && nh_sip->sip_cseq)
	  seq = nh_sip->sip_cseq->cs_seq;
	/* ACK/CANCEL cannot be restarted so we do not copy message */
	copy = 0;
      }
      else
	msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
    }
    msg = nta_msg_create(nua->nua_nta, 0);
    tl_gets(nh->nh_tags, NUTAG_URL_REF(url), TAG_END());
    sip_add_tl(msg, sip_object(msg), TAG_NEXT(nh->nh_tags));
  }

  ta_start(ta, tag, value);

  sip = sip_object(msg);
  if (!sip)
    goto error;

  {
    tl_gets(ta_args(ta),
	    NUTAG_URL_REF(url),
	    NUTAG_USE_DIALOG_REF(use_dialog),
	    /* NUTAG_COPY_REF(copy), */
	    NUTAG_ADD_CONTACT_REF(add_contact),
	    TAG_END());

    if (method == sip_method_register && url == NULL && !sip->sip_request) {
      tl_gets(ta_args(ta), NUTAG_REGISTRAR_REF(url), TAG_END());
      if (url == NULL)
	tl_gets(nh->nh_tags, NUTAG_REGISTRAR_REF(url), TAG_END());
      if (url == NULL)
	url = (url_string_t *)nua->nua_registrar;
    }

    if (seq != -1) {
      sip_cseq_t *cseq;
     
      assert(method != sip_method_unknown || name || sip->sip_request);
      
      if (method || name)
	cseq = sip_cseq_create(msg_home(msg), seq, method, name);
      else 
	cseq = sip_cseq_create(msg_home(msg), seq, 
			       sip->sip_request->rq_method, 
			       sip->sip_request->rq_method_name);

      sip_header_insert(msg, sip, (sip_header_t *)cseq);
    }

    if (ds->ds_leg) {
      add_service_route = 0;

      /* If leg has established route, use it, not original URL */
      if (ds->ds_route)
	url = NULL;

      if (sip_add_tl(msg, sip, ta_tags(ta)) < 0 ||
	  nta_msg_request_complete(msg, ds->ds_leg, method, name, url) < 0)
	goto error;
    }
    else {
      nta_leg_t *leg = nua->nua_dhandle->nh_ds->ds_leg;

      if (sip_add_tl(msg, sip, ta_tags(ta)) < 0
	  || (ds->ds_remote_tag && ds->ds_remote_tag[0] && 
	      sip_to_tag(nh->nh_home, sip->sip_to, ds->ds_remote_tag) < 0)
	  || (sip->sip_from == NULL &&
{'fraction_non_alphanumeric': 0.17058468957203135, 'fraction_numerical': 0.0066693888662038925, 'mean_word_length': 3.1908409387222947, 'pattern_counts': {'":': 0, '<': 119, '<?xml version=': 0, '>': 754, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1662335', 'n_tokens_mistral': 22554, 'n_tokens_neox': 21274, 'n_words': 4244}