sip_pref_util.c 15.1 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
 * 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 sip_pref_util.c
26
 *
Pekka Pessi's avatar
Pekka Pessi committed
27 28 29 30 31 32 33 34 35
 * SIP callercaps and callerprefs utility functions.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>.
 *
 * @date Created: Tue Nov  2 16:39:33 EET 2004 ppessi
 */

#include "config.h"

36
#include <stdio.h>
Pekka Pessi's avatar
Pekka Pessi committed
37 38 39 40 41 42
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <float.h>

43 44 45 46
#include "sofia-sip/sip_parser.h"
#include <sofia-sip/sip_header.h>
#include <sofia-sip/sip_util.h>
#include <sofia-sip/sip_status.h>
Pekka Pessi's avatar
Pekka Pessi committed
47

48 49
static double parse_number(char const *str, char **return_end);

Pekka Pessi's avatar
Pekka Pessi committed
50
/** Parse a single preference */
51 52
int sip_prefs_parse(union sip_pref *sp,
		    char const **in_out_s,
Pekka Pessi's avatar
Pekka Pessi committed
53 54 55
		    int *return_negation)
{
  char const *s;
56
  size_t n;
Pekka Pessi's avatar
Pekka Pessi committed
57 58 59 60 61 62 63 64 65 66 67 68
  enum sp_type old_type;

  assert(sp && in_out_s && *in_out_s && return_negation);

  old_type = sp->sp_type;
  sp->sp_type = sp_error;

  s = *in_out_s;
  if (!s)
    return 0;

  if (old_type == sp_init) {
69
    if (s[0] == '\0' ||
70 71
	su_casematch(s, "TRUE") ||
	su_casematch(s, "\"TRUE\"")) {
Pekka Pessi's avatar
Pekka Pessi committed
72 73 74 75 76 77 78
      /* Boolean */
      sp->sp_type = sp_literal;
      sp->sp_literal.spl_value = "TRUE";
      sp->sp_literal.spl_length = 4;
      *return_negation = 0;
      *in_out_s = s + strlen(s);
      return 1;
79 80
    } else if (su_casematch(s, "FALSE") ||
	       su_casematch(s, "\"FALSE\"")) {
Pekka Pessi's avatar
Pekka Pessi committed
81 82 83 84 85 86 87 88
      /* Boolean */
      sp->sp_type = sp_literal;
      sp->sp_literal.spl_value = "FALSE";
      sp->sp_literal.spl_length = 5;
      *return_negation = 0;
      *in_out_s = s + strlen(s);
      return 1;
    } else if (s[0] == '"' && s[1] != '\0') {
Kai Samposalo's avatar
Kai Samposalo committed
89 90
      for (s++; IS_LWS(s[0]); s++)
        {}
Pekka Pessi's avatar
Pekka Pessi committed
91
    } else
92
      old_type = sp_error;
Pekka Pessi's avatar
Pekka Pessi committed
93 94 95 96 97 98 99 100 101
  } else if (!s[0]) {
    sp->sp_type = sp_init;
    return 0;
  }

  if (old_type == sp_error)
    return 0;

  if ((*return_negation = s[0] == '!'))
Kai Samposalo's avatar
Kai Samposalo committed
102 103
      for (s++; IS_LWS(s[0]); s++)
        {}
Pekka Pessi's avatar
Pekka Pessi committed
104 105 106 107 108 109

  if (*s == '#') {
    /* Numeric */
    double n1, n2;
    char s0, *e;

Kai Samposalo's avatar
Kai Samposalo committed
110 111
    for (s++; IS_LWS(s[0]); s++)
      {}
112

Pekka Pessi's avatar
Pekka Pessi committed
113 114 115
    s0 = s[0];

    if (s0 == '=')
116
      sp->sp_type = sp_range, n1 = n2 = parse_number(s = s + 1, &e);
Pekka Pessi's avatar
Pekka Pessi committed
117
    else if (s0 == '<' && s[1] == '=')
118
      sp->sp_type = sp_range, n1 = -DBL_MAX, n2 = parse_number(s = s + 2, &e);
Pekka Pessi's avatar
Pekka Pessi committed
119
    else if (s0 == '>' && s[1] == '=')
120 121 122
      sp->sp_type = sp_range, n1 = parse_number(s = s + 2, &e), n2 = DBL_MAX;
    else if (((n1 = parse_number(s, &e)) != 0.0 || s != e) && e[0] == ':')
      sp->sp_type = sp_range, n2 = parse_number(s = e + 1, &e);
Pekka Pessi's avatar
Pekka Pessi committed
123 124
    else
      /* Error in conversion */
125
      sp->sp_type = sp_error, n1 = DBL_MAX, n2 = -DBL_MAX;
Pekka Pessi's avatar
Pekka Pessi committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

    if (s == e && (n1 == 0.0 || n2 == 0.0))
      sp->sp_type = sp_error;      /* Error in conversion */

    sp->sp_range.spr_lower = n1;
    sp->sp_range.spr_upper = n2;

    s = e;
  } else if (*s == '<') {
    /* Quoted string */
    n = strcspn(++s, ">");
    sp->sp_type = sp_string;
    sp->sp_string.sps_value = s;
    sp->sp_string.sps_length = n;
    s += n + 1;
  } else if ((n = span_token(s))) {
    /* Literal */
    sp->sp_type = sp_literal;
    sp->sp_literal.spl_value = s;
    sp->sp_literal.spl_length = n;
    s += n;
  }

Kai Samposalo's avatar
Kai Samposalo committed
149 150
  for (; IS_LWS(s[0]); s++)
    {}
Pekka Pessi's avatar
Pekka Pessi committed
151 152

  if (s[0] == ',' || (s[0] == '"' && s[1] == '\0'))
Kai Samposalo's avatar
Kai Samposalo committed
153 154
    for (s++; IS_LWS(s[0]); s++)
      {}
Pekka Pessi's avatar
Pekka Pessi committed
155 156 157
  else
    old_type = sp_error;

158
  if (old_type != sp_init && old_type != sp->sp_type)
Pekka Pessi's avatar
Pekka Pessi committed
159
    sp->sp_type = sp_error;
160

Pekka Pessi's avatar
Pekka Pessi committed
161 162 163 164 165
  *in_out_s = s;

  return sp->sp_type != sp_error;
}

166 167 168 169 170 171 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
/** Parse number:
 * number          =  [ "+" / "-" ] 1*DIGIT ["." 0*DIGIT]
 */
static double parse_number(char const *str, char **return_end)
{
  double value = 0.0;
  double decimal = 0.1;
  char d, sign = '+';

  if (return_end)
    *return_end = (char *)str;

  d = *str;

  if (d == '+' || d == '-')
    sign = d, d = *++str;

  if (!('0' <= d && d <= '9'))
    return value;

  for (; '0' <= d && d <= '9'; d = *++str)
    value = value * 10 + (d - '0');

  if (d == '.') for (d = *++str; '0' <= d && d <= '9'; d = *++str) {
    value += (d - '0') * decimal; decimal *= 0.1;
  }

  if (value > DBL_MAX)
    value = DBL_MAX;

  if (sign == '-')
    value = -value;

  if (return_end)
    *return_end = (char *)str;

  return value;
}


Pekka Pessi's avatar
Pekka Pessi committed
206
/** Return true if preferences match */
207
int sip_prefs_match(union sip_pref const *a,
Pekka Pessi's avatar
Pekka Pessi committed
208 209 210 211 212 213 214 215
		    union sip_pref const *b)
{
  if (!a || !b)
    return 0;
  if (a->sp_type != b->sp_type)
    return 0;
  switch (a->sp_type) {
  default:
216
  case sp_error:
Pekka Pessi's avatar
Pekka Pessi committed
217 218
    return 0;
  case sp_literal:
219
    return
Pekka Pessi's avatar
Pekka Pessi committed
220
      a->sp_literal.spl_length == b->sp_literal.spl_length &&
221 222
      su_casenmatch(a->sp_literal.spl_value, b->sp_literal.spl_value,
		  a->sp_literal.spl_length);
Pekka Pessi's avatar
Pekka Pessi committed
223
  case sp_string:
224
    return
Pekka Pessi's avatar
Pekka Pessi committed
225 226 227 228
      a->sp_string.sps_length == b->sp_string.sps_length &&
      strncmp(a->sp_string.sps_value, b->sp_string.sps_value,
	      a->sp_string.sps_length) == 0;
  case sp_range:
229
    return
Pekka Pessi's avatar
Pekka Pessi committed
230 231 232 233 234 235 236
      a->sp_range.spr_lower <= b->sp_range.spr_upper &&
      a->sp_range.spr_upper >= b->sp_range.spr_lower;
  }
}

/**Find a matching parameter-value pair from a parameter list.
 *
237
 * Check if the given feature values match with each other.
Pekka Pessi's avatar
Pekka Pessi committed
238 239 240 241 242
 *
 * @param pvalue first feature parameter
 * @param nvalue second feature parameter
 * @param return_parse_error return-value parameter for error (may be NULL)
 *
243 244
 * @retval 1 if given feature parameters match
 * @retval 0 if there is no match or a parse or type error occurred.
Pekka Pessi's avatar
Pekka Pessi committed
245 246
 *
 * If there is a parsing or type error, 0 is returned and @a
247 248 249
 * *return_parse_error is set to -1.
 *
 * @sa sip_prefs_parse(), sip_prefs_match(), union #sip_pref.
Pekka Pessi's avatar
Pekka Pessi committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
 */
int sip_prefs_matching(char const *pvalue,
		       char const *nvalue,
		       int *return_parse_error)
{
  int error;
  char const *p;
  union sip_pref np[1], pp[1];
  int n_negated, p_negated;

  if (!return_parse_error)
    return_parse_error = &error;

  if (!pvalue || !nvalue)
    return 0;

  memset(np, 0, sizeof np);

268
  /* Usually nvalue is from Accept/Reject-Contact,
Pekka Pessi's avatar
Pekka Pessi committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
     pvalue is from Contact */
  while (sip_prefs_parse(np, &nvalue, &n_negated)) {
    memset(pp, 0, sizeof pp);
    p = pvalue;

    while (sip_prefs_parse(pp, &p, &p_negated)) {
      if (pp->sp_type != np->sp_type) /* Types do not match */
	return 0;

      if (sip_prefs_match(np, pp) /* We found matching value */
	  ? !p_negated	/* without negative */
	  : p_negated)	/* Negative did not match */
	break;
    }

    if (pp->sp_type == sp_error)
      return *return_parse_error = -1, 0;

    if (pp->sp_type != sp_init /* We found matching value */
	? !n_negated		/* and we expected one */
	: n_negated)		/* We found none and expected none */
      return 1;
  }

  if (np->sp_type == sp_error)
    *return_parse_error = -1;

  return 0;
}

299
/** Check if the parameter is a valid feature tag.
300 301 302 303 304 305 306 307 308 309 310 311
 *
 * A feature tag is a parameter starting with a single plus, or a well-known
 * feature tag listed in @RFC3841: "audio", "automata", "application",
 * "class", "control", "duplex", "data", "description", "events", "isfocus",
 * "language", "mobility", "methods", "priority", "schemes", "type", or
 * "video". However, well-known feature tag can not start with plus. So,
 * "+alarm" or "audio" is a feature tag, "alarm", "++alarm", or "+audio" are
 * not.
 *
 * @retval 1 if string is a feature tag parameter
 * @retval 0 otherwise
 */
Pekka Pessi's avatar
Pekka Pessi committed
312 313 314
int sip_is_callerpref(char const *param)
{
#define MATCH(s) \
315
  (su_casenmatch(param + 1, s + 1, strlen(s) - 1) && \
Pekka Pessi's avatar
Pekka Pessi committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 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
   (param[strlen(s)] == '=' || param[strlen(s)] == '\0'))

  int xor = 0, base = 0;

  if (!param || !param[0])
    return 0;

  if (param[0] == '+')
    param++, xor = 1;

  switch (param[0]) {
  case 'a': case 'A':
    base = MATCH("audio") || MATCH("automata") || MATCH("application") ||
      MATCH("actor");
    break;
  case 'c': case 'C':
    base = MATCH("class") || MATCH("control");
    break;
  case 'd': case 'D':
    base = MATCH("duplex") || MATCH("data") || MATCH("description");
    break;
  case 'e': case 'E':
    base = MATCH("events");
    break;
  case 'i': case 'I':
    base = MATCH("isfocus");
    break;
  case 'l': case 'L':
    base = MATCH("language");
    break;
  case 'm': case 'M':
    base = MATCH("mobility") || MATCH("methods");
    break;
  case 'p': case 'P':
    base = MATCH("priority");
    break;
  case 's': case 'S':
    base = MATCH("schemes");
    break;
  case 't': case 'T':
    base = MATCH("type");
    break;
  case 'v': case 'V':
    base = MATCH("video");
    break;
  default:
    base = 0;
    break;
  }
#undef MATCH

  return base ^ xor;
}

370
/** Check if @Contact is immune to callerprefs. */
371
int sip_contact_is_immune(sip_contact_t const *m)
Pekka Pessi's avatar
Pekka Pessi committed
372 373 374 375 376 377 378 379 380 381 382 383
{
  unsigned i;

  if (m->m_params)
    for (i = 0; m->m_params[i]; i++) {
      if (sip_is_callerpref(m->m_params[i]))
	return 0;
    }

  return 1;
}

384
/**Check if @Contact matches by @AcceptContact.
385
 *
386 387 388 389 390 391 392 393 394 395 396 397
 * Matching @AcceptContact and @Contact headers is done as explained in
 * @RFC3841 section 7.2.4. The caller score can be calculated from the
 * returned S and N values.
 *
 * @par Matching
 * The @AcceptContact header contains number of feature tag parameters. The
 * count of feature tags is returned in @a return_N. For each feature tag in
 * @AcceptContact, the feature tag with same name is searched from the
 * @Contact header. If both headers contain the feature tag with same name,
 * their values are compared. If the value in @AcceptContact does not match
 * with the value in @Contact, there is mismatch and 0 is returned. If they
 * match, S is increased by 1.
Pekka Pessi's avatar
Pekka Pessi committed
398
 *
399 400
 * @param m   pointer to @Contact header structure
 * @param cp   pointer to @AcceptContact header structure
401
 * @param return_N   return-value parameter for number of
402
 *                   feature tags in @AcceptContact
403
 * @param return_S   return-value parameter for number of
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
 *                   matching feature tags
 * @param return_error   return-value parameter for parsing error
 *
 * For example,
 * @code
 * if (sip_contact_accept(contact, accept_contact, &S, &N, &error)) {
 *   if (N == 0)
 *     score == 1.0;
 *   else
 *     score = (double)S / (double)N;
 *   if (accept_contact->cp_explicit) {
 *     if (accept_contact->cp_require)
 *       goto drop;
 *     else
 *       score = 0.0;
 *   }
 * }
 * else if (!error) {
 *   score = 0.0;
 * }
 * @endcode
 *
 * @retval 1 if @Contact matches
 * @return @a return_S contains number of matching feature tags
 * @return @a return_N contains number of feature tags in @AcceptContact
 * @retval 0 if @Contact does not match
 * @return @a return_error contains -1 if feature tag value was malformed
 *
 * @sa @RFC3841 section 7.2.4, sip_contact_score(), sip_contact_reject(),
 * sip_contact_is_immune(), sip_contact_immunize(), sip_is_callerpref(),
 * sip_prefs_matching().
Pekka Pessi's avatar
Pekka Pessi committed
435
 */
436
int sip_contact_accept(sip_contact_t const *m,
Pekka Pessi's avatar
Pekka Pessi committed
437 438 439 440 441 442
		       sip_accept_contact_t const *cp,
		       unsigned *return_S,
		       unsigned *return_N,
		       int *return_error)
{
  char const *cap, *acc;
443 444
  unsigned i, S, N;
  size_t eq;
Pekka Pessi's avatar
Pekka Pessi committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

  if (!return_N) return_N = &N;
  if (!return_S) return_S = &S;

  *return_S = 0, *return_N = 0;

  if (!m || !cp || !m->m_params || !cp->cp_params)
    return 1;

  for (i = 0, S = 0, N = 0; cp->cp_params[i]; i++) {
    acc = cp->cp_params[i];
    if (!sip_is_callerpref(acc))
      continue;

    N++;

461
    cap = msg_params_find(m->m_params, acc);
Pekka Pessi's avatar
Pekka Pessi committed
462 463 464 465 466

    if (cap) {
      eq = strcspn(acc, "=");
      acc += eq + (acc[eq] == '=');

467
      if (!sip_prefs_matching(cap, acc, return_error))
Pekka Pessi's avatar
Pekka Pessi committed
468
	return 0;
469

Pekka Pessi's avatar
Pekka Pessi committed
470 471 472 473 474
      S++;
    }
  }

  *return_S = S; /* Matched feature tags */
475
  *return_N = N; /* Number of feature tags in @AcceptContact */
Pekka Pessi's avatar
Pekka Pessi committed
476

477
  return 1;
Pekka Pessi's avatar
Pekka Pessi committed
478 479 480
}


481 482 483 484 485 486 487 488 489 490 491
/** Check if @Contact is rejected by @RejectContact.
 *
 * @param m pointer to @Contact header
 * @param reject pointer to @RejectContact header
 *
 * @retval 1 when rejecting
 * @retval 0 when @Contact does not match with @RejectContact
 *
 * @sa sip_contact_score(), sip_contact_accept(), sip_contact_immunize(),
 * sip_contact_is_immune(), @RFC3841, @RejectContact, @Contact
 */
492
int sip_contact_reject(sip_contact_t const *m,
Pekka Pessi's avatar
Pekka Pessi committed
493 494 495 496 497 498 499 500 501 502 503
		       sip_reject_contact_t const *reject)
{
  unsigned S, N;
  int error;

  if (!m || !m->m_params || !reject || !reject->cp_params)
    return 0;

  return sip_contact_accept(m, reject, &S, &N, &error) && S == N && N > 0;
}

504 505 506 507 508 509 510 511 512 513
/**Immunize @Contact to callerprefs.
 *
 * Make a copy of @Contact header @a m and remove all parameters which
 * affect caller preferences.
 *
 * @param home   home object used when allocating copy
 * @param m   pointer to @Contact header structure to immunize
 *
 * @retval pointer to immunized copy if successful
 * @retval NULL upon an error
514
 *
515 516 517
 * @sa @RFC3841, sip_is_callerpref(), sip_contact_score(),
 * sip_contact_accept(), sip_contact_reject(), @Contact
 */
Pekka Pessi's avatar
Pekka Pessi committed
518 519 520 521
sip_contact_t *sip_contact_immunize(su_home_t *home, sip_contact_t const *m)
{
  unsigned i, j;
  sip_contact_t m0[1], *m1;
Pekka Pessi's avatar
Pekka Pessi committed
522
  msg_param_t *params;
Pekka Pessi's avatar
Pekka Pessi committed
523 524 525 526 527 528 529 530 531 532 533

  if (!m)
    return NULL;

  *m0 = *m, m0->m_next = NULL;

  m1 = sip_contact_copy(home, m0);

  if (m1 == NULL || !m1->m_params)
    return m1;

Pekka Pessi's avatar
Pekka Pessi committed
534
  params = (msg_param_t *)m1->m_params;
Pekka Pessi's avatar
Pekka Pessi committed
535 536 537 538 539 540 541 542 543 544 545

  for (i = 0, j = 0; params[i]; i++) {
    if (!sip_is_callerpref(params[i]))
      params[j++] = params[i];
  }

  params[j] = NULL;

  return m1;
}

546 547 548
/** Calculate score for contact.
 *
 * The caller preference score is an integer in range of 0 to 1000.
549
 *
550 551
 * @retval -1 if the contact is rejected
 * @retval 1000 if contact is immune to caller preferences
Pekka Pessi's avatar
Pekka Pessi committed
552
 * @retval 0..1000 reflecting @RFC3841 score in 0.000 - 1.000.
553 554 555 556
 *
 * @sa sip_q_value(),
 * sip_contact_accept(), sip_contact_reject(), sip_contact_is_immune(),
 * sip_contact_immunize(), sip_is_callerpref(), sip_prefs_matching(),
Pekka Pessi's avatar
Pekka Pessi committed
557
 * @RFC3841, @AcceptContact, @RejectContact, @Contact
558
 */
Pekka Pessi's avatar
Pekka Pessi committed
559 560 561 562 563 564 565 566
int sip_contact_score(sip_contact_t const *m,
		      sip_accept_contact_t const *ac,
		      sip_reject_contact_t const *rc)
{
  unsigned long S_total = 0;
  unsigned M = 0, scale = 1000;
  int error = 0;

567
  if (sip_contact_is_immune(m))
Pekka Pessi's avatar
Pekka Pessi committed
568 569 570
    return 1000;		/* Immune */

  for (; rc; rc = rc->cp_next)
571
    if (sip_contact_reject(m, rc))
Pekka Pessi's avatar
Pekka Pessi committed
572 573 574 575 576 577
      break;
  if (rc)
    return -1;			/* Rejected */

  for (; ac; ac = ac->cp_next) {
    unsigned S, N;
578

Pekka Pessi's avatar
Pekka Pessi committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    if (!sip_contact_accept(m, ac, &S, &N, &error)) {
      if (ac->cp_require)
	return 0;		/* Discarded */
      continue;
    }

    M++;

    /* Apply score */
    if (S < N && ac->cp_explicit) {
      S = 0;
      if (ac->cp_require)
	return 0;		/* Dropped */
    }

594
    if (S > 0 && N > 0)
Pekka Pessi's avatar
Pekka Pessi committed
595 596 597
      S_total += sip_q_value(ac->cp_q) * (scale * S / N + (2 * S >= N));
  }

598
  if (!M)
Pekka Pessi's avatar
Pekka Pessi committed
599 600 601 602 603 604 605 606 607
    return 0;

  S_total /= M;

  if (S_total < scale * 1000)
    return S_total / scale;
  else
    return 1000;
}