core: detect Skype for Business server
[siplcs.git] / src / core / sip-transport.c
blobd77b1f5d9a38626a156251559b066d18b4af58db
1 /**
2 * @file sip-transport.c
4 * pidgin-sipe
6 * Copyright (C) 2010-2016 SIPE Project <http://sipe.sourceforge.net/>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /**
24 * This module incapsulates SIP (RFC3261) protocol and provides
25 * higher level API (a layer) to XML-based SIPE (SIP with Extensions).
26 * Underlying leyer for this is TCP/SSL layer.
28 * A diagram in pseudographics:
30 * === SIPE (XML-based) layer ======================
31 * === SIP RFC3261 transport layer (This module) ===
32 * === TCP/SSL layer ===============================
34 * Authentication (Kerberos and NTLM) is applicable to this layer only.
35 * The same with message integtity (signing). No sip-sec* code should
36 * be used ourside of this module.
38 * SIP errors as codes(both as a return codes and network conditions) should be
39 * escalated to higher leyer (SIPE). Network conditions include no response
40 * within timeout interval.
42 * This module should support redirect internally. No escalations to higher
43 * layers needed.
45 * NO SIP-messages (headers) composing and processing should be outside of
46 * this module (!) Like headers: Via, Route, Contact, Authorization, etc.
47 * It's all irrelevant to higher layer responsibilities.
49 * Specification references:
51 * - [MS-SIPAE]: http://msdn.microsoft.com/en-us/library/cc431510.aspx
54 #ifdef HAVE_CONFIG_H
55 #include "config.h"
56 #endif
58 #include <stdlib.h>
59 #include <string.h>
60 #include <stdio.h>
62 #include <glib.h>
64 #include "sipe-common.h"
65 #include "sipmsg.h"
66 #include "sip-sec.h"
67 #include "sip-sec-digest.h"
68 #include "sip-transport.h"
69 #include "sipe-backend.h"
70 #include "sipe-core.h"
71 #include "sipe-core-private.h"
72 #include "sipe-certificate.h"
73 #include "sipe-dialog.h"
74 #include "sipe-incoming.h"
75 #include "sipe-lync-autodiscover.h"
76 #include "sipe-nls.h"
77 #include "sipe-notify.h"
78 #include "sipe-schedule.h"
79 #include "sipe-sign.h"
80 #include "sipe-subscriptions.h"
81 #include "sipe-utils.h"
82 #include "uuid.h"
84 struct sip_auth {
85 guint type;
86 struct sip_sec_context *gssapi_context;
87 gchar *gssapi_data;
88 gchar *opaque;
89 const gchar *protocol;
90 gchar *realm;
91 gchar *sts_uri;
92 gchar *target;
93 guint version;
94 guint retries;
95 guint ntlm_num;
96 guint expires;
97 gboolean can_retry;
100 /* sip-transport.c private data */
101 struct sip_transport {
102 struct sipe_transport_connection *connection;
104 gchar *server_name;
105 guint server_port;
106 gchar *server_version;
108 gchar *epid;
109 gchar *ip_address; /* local IP address of transport socket */
111 gchar *user_agent;
113 GSList *transactions;
115 struct sip_auth registrar;
116 struct sip_auth proxy;
118 guint cseq;
119 guint register_attempt;
121 guint keepalive_timeout;
122 time_t last_message;
124 gboolean processing_input; /* whether full header received */
125 gboolean auth_incomplete; /* whether authentication not completed */
126 gboolean auth_retry; /* whether next authentication should be tried */
127 gboolean reregister_set; /* whether reregister timer set */
128 gboolean reauthenticate_set; /* whether reauthenticate timer set */
129 gboolean subscribed; /* whether subscribed to events, except buddies presence */
130 gboolean deregister; /* whether in deregistration */
133 /* Keep in sync with sipe_transport_type! */
134 static const char *transport_descriptor[] = { "", "tls", "tcp"};
135 #define TRANSPORT_DESCRIPTOR (transport_descriptor[transport->connection->type])
137 static char *genbranch()
139 return g_strdup_printf("z9hG4bK%04X%04X%04X%04X%04X",
140 rand() & 0xFFFF, rand() & 0xFFFF, rand() & 0xFFFF,
141 rand() & 0xFFFF, rand() & 0xFFFF);
144 static void sipe_auth_free(struct sip_auth *auth)
146 g_free(auth->opaque);
147 auth->opaque = NULL;
148 auth->protocol = NULL;
149 g_free(auth->realm);
150 auth->realm = NULL;
151 g_free(auth->sts_uri);
152 auth->sts_uri = NULL;
153 g_free(auth->target);
154 auth->target = NULL;
155 auth->version = 0;
156 auth->type = SIPE_AUTHENTICATION_TYPE_UNSET;
157 auth->retries = 0;
158 auth->expires = 0;
159 auth->can_retry = FALSE;
160 g_free(auth->gssapi_data);
161 auth->gssapi_data = NULL;
162 sip_sec_destroy_context(auth->gssapi_context);
163 auth->gssapi_context = NULL;
166 static void sipe_make_signature(struct sipe_core_private *sipe_private,
167 struct sipmsg *msg)
169 struct sip_transport *transport = sipe_private->transport;
170 if (sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
171 struct sipmsg_breakdown msgbd;
172 gchar *signature_input_str;
173 msgbd.msg = msg;
174 sipmsg_breakdown_parse(&msgbd, transport->registrar.realm, transport->registrar.target,
175 transport->registrar.protocol);
176 msgbd.rand = g_strdup_printf("%08x", g_random_int());
177 transport->registrar.ntlm_num++;
178 msgbd.num = g_strdup_printf("%d", transport->registrar.ntlm_num);
179 signature_input_str = sipmsg_breakdown_get_string(transport->registrar.version, &msgbd);
180 if (signature_input_str != NULL) {
181 char *signature_hex = sip_sec_make_signature(transport->registrar.gssapi_context, signature_input_str);
182 g_free(msg->signature);
183 msg->signature = signature_hex;
184 g_free(msg->rand);
185 msg->rand = g_strdup(msgbd.rand);
186 g_free(msg->num);
187 msg->num = g_strdup(msgbd.num);
188 g_free(signature_input_str);
190 sipmsg_breakdown_free(&msgbd);
194 static const gchar *const auth_type_to_protocol[] = {
195 NULL, /* SIPE_AUTHENTICATION_TYPE_UNSET */
196 NULL, /* SIPE_AUTHENTICATION_TYPE_BASIC */
197 "NTLM", /* SIPE_AUTHENTICATION_TYPE_NTLM */
198 "Kerberos", /* SIPE_AUTHENTICATION_TYPE_KERBEROS */
199 NULL, /* SIPE_AUTHENTICATION_TYPE_NEGOTIATE */
200 "TLS-DSK", /* SIPE_AUTHENTICATION_TYPE_TLS_DSK */
201 NULL, /* SIPE_AUTHENTICATION_TYPE_AUTOMATIC */
203 #define AUTH_PROTOCOLS (sizeof(auth_type_to_protocol)/sizeof(gchar *))
205 static gchar *msg_signature_to_auth(struct sip_auth *auth,
206 struct sipmsg *msg)
208 return(g_strdup_printf("%s qop=\"auth\", opaque=\"%s\", realm=\"%s\", targetname=\"%s\", crand=\"%s\", cnum=\"%s\", response=\"%s\"",
209 auth->protocol,
210 auth->opaque, auth->realm, auth->target,
211 msg->rand, msg->num, msg->signature));
214 static gboolean auth_can_retry(struct sip_transport *transport,
215 const struct sip_auth *auth)
217 /* NTLM is the scheme with lowest priority - don't retry */
218 gboolean retry =
219 auth->can_retry &&
220 (auth->type != SIPE_AUTHENTICATION_TYPE_NTLM);
221 if (retry)
222 transport->auth_retry = TRUE;
223 return(retry);
226 static void initialize_auth_retry(struct sipe_core_private *sipe_private,
227 struct sip_auth *auth)
229 struct sip_transport *transport = sipe_private->transport;
231 if (auth_can_retry(transport, auth)) {
232 if (auth->gssapi_context) {
233 /* need to drop context for retry */
234 sip_sec_destroy_context(auth->gssapi_context);
235 auth->gssapi_context = NULL;
237 } else {
238 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
239 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
240 _("Failed to authenticate to server"));
244 static gchar *initialize_auth_context(struct sipe_core_private *sipe_private,
245 struct sip_auth *auth,
246 struct sipmsg *msg)
248 struct sip_transport *transport = sipe_private->transport;
249 gchar *ret;
250 gchar *gssapi_data = NULL;
251 gchar *sign_str;
252 gchar *gssapi_str;
253 gchar *opaque_str;
254 gchar *version_str;
257 * If transport is de-registering when we reach this point then we
258 * are in the middle of the previous authentication context setup
259 * attempt. So we shouldn't try another attempt.
261 if (transport->deregister)
262 return NULL;
264 /* Create security context or handshake continuation? */
265 if (auth->gssapi_context) {
266 /* Perform next step in authentication handshake */
267 gboolean status = sip_sec_init_context_step(auth->gssapi_context,
268 auth->target,
269 auth->gssapi_data,
270 &gssapi_data,
271 &auth->expires);
273 /* If authentication is completed gssapi_data can be NULL */
274 if (!(status &&
275 (sip_sec_context_is_ready(auth->gssapi_context) || gssapi_data))) {
276 SIPE_DEBUG_ERROR_NOFORMAT("initialize_auth_context: security context continuation failed");
277 g_free(gssapi_data);
278 initialize_auth_retry(sipe_private, auth);
279 return NULL;
282 } else {
283 /* Create security context */
284 gpointer password = sipe_private->password;
286 /* For TLS-DSK the "password" is a certificate */
287 if (auth->type == SIPE_AUTHENTICATION_TYPE_TLS_DSK) {
288 password = sipe_certificate_tls_dsk_find(sipe_private,
289 auth->target);
291 if (!password) {
292 if (auth->sts_uri) {
293 SIPE_DEBUG_INFO("initialize_auth_context: TLS-DSK Certificate Provisioning URI %s",
294 auth->sts_uri);
295 if (!sipe_certificate_tls_dsk_generate(sipe_private,
296 auth->target,
297 auth->sts_uri)) {
298 gchar *tmp = g_strdup_printf(_("Can't request certificate from %s"),
299 auth->sts_uri);
300 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
301 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
302 tmp);
303 g_free(tmp);
305 } else {
306 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
307 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
308 _("No URI for certificate provisioning service provided"));
311 /* we can't authenticate the message yet */
312 transport->auth_incomplete = TRUE;
314 return(NULL);
315 } else {
316 SIPE_DEBUG_INFO("initialize_auth_context: TLS-DSK certificate for target '%s' found.",
317 auth->target);
321 auth->gssapi_context = sip_sec_create_context(auth->type,
322 SIPE_CORE_PRIVATE_FLAG_IS(SSO),
323 FALSE, /* connection-less for SIP */
324 sipe_private->authuser,
325 password);
327 if (auth->gssapi_context) {
328 sip_sec_init_context_step(auth->gssapi_context,
329 auth->target,
330 NULL,
331 &gssapi_data,
332 &(auth->expires));
335 /* if auth->gssapi_context is NULL then gssapi_data is still NULL */
336 if (!gssapi_data) {
337 SIPE_DEBUG_ERROR_NOFORMAT("initialize_auth_context: security context initialization failed");
338 initialize_auth_retry(sipe_private, auth);
339 return NULL;
343 if ((auth->version > 3) &&
344 sip_sec_context_is_ready(auth->gssapi_context)) {
345 sipe_make_signature(sipe_private, msg);
346 sign_str = g_strdup_printf(", crand=\"%s\", cnum=\"%s\", response=\"%s\"",
347 msg->rand, msg->num, msg->signature);
348 } else {
349 sign_str = g_strdup("");
352 if (gssapi_data) {
353 gssapi_str = g_strdup_printf(", gssapi-data=\"%s\"",
354 gssapi_data);
355 g_free(gssapi_data);
356 } else {
357 gssapi_str = g_strdup("");
360 opaque_str = auth->opaque ? g_strdup_printf(", opaque=\"%s\"", auth->opaque) : g_strdup("");
362 if (auth->version > 2) {
363 version_str = g_strdup_printf(", version=%d", auth->version);
364 } else {
365 version_str = g_strdup("");
368 ret = g_strdup_printf("%s qop=\"auth\"%s, realm=\"%s\", targetname=\"%s\"%s%s%s",
369 auth->protocol, opaque_str,
370 auth->realm, auth->target,
371 gssapi_str, version_str, sign_str);
372 g_free(version_str);
373 g_free(opaque_str);
374 g_free(gssapi_str);
375 g_free(sign_str);
377 return(ret);
380 static gchar *auth_header(struct sipe_core_private *sipe_private,
381 struct sip_auth *auth,
382 struct sipmsg *msg)
384 gchar *ret = NULL;
387 * If the message is already signed then we have an authentication
388 * context, i.e. the authentication handshake is complete. Generate
389 * authentication header from message signature.
391 if (msg->signature) {
392 ret = msg_signature_to_auth(auth, msg);
395 * We should reach this point only when the authentication context
396 * needs to be initialized.
398 } else {
399 ret = initialize_auth_context(sipe_private, auth, msg);
402 return(ret);
405 static void fill_auth(const gchar *hdr, struct sip_auth *auth)
407 const gchar *param;
409 /* skip authentication identifier */
410 hdr = strchr(hdr, ' ');
411 if (!hdr) {
412 SIPE_DEBUG_ERROR_NOFORMAT("fill_auth: corrupted authentication header");
413 return;
415 while (*hdr == ' ')
416 hdr++;
418 /* start of next parameter value */
419 while ((param = strchr(hdr, '=')) != NULL) {
420 const gchar *end;
422 /* parameter value type */
423 param++;
424 if (*param == '"') {
425 /* string: xyz="..."(,) */
426 end = strchr(++param, '"');
427 if (!end) {
428 SIPE_DEBUG_ERROR("fill_auth: corrupted string parameter near '%s'", hdr);
429 break;
431 } else {
432 /* number: xyz=12345(,) */
433 end = strchr(param, ',');
434 if (!end) {
435 /* last parameter */
436 end = param + strlen(param);
440 #if 0
441 SIPE_DEBUG_INFO("fill_auth: hdr '%s'", hdr);
442 SIPE_DEBUG_INFO("fill_auth: param '%s'", param);
443 SIPE_DEBUG_INFO("fill_auth: end '%s'", end);
444 #endif
446 /* parameter type */
447 if (g_str_has_prefix(hdr, "gssapi-data=\"")) {
448 g_free(auth->gssapi_data);
449 auth->gssapi_data = g_strndup(param, end - param);
450 } else if (g_str_has_prefix(hdr, "opaque=\"")) {
451 g_free(auth->opaque);
452 auth->opaque = g_strndup(param, end - param);
453 } else if (g_str_has_prefix(hdr, "realm=\"")) {
454 g_free(auth->realm);
455 auth->realm = g_strndup(param, end - param);
456 } else if (g_str_has_prefix(hdr, "sts-uri=\"")) {
457 /* Only used with SIPE_AUTHENTICATION_TYPE_TLS_DSK */
458 g_free(auth->sts_uri);
459 auth->sts_uri = g_strndup(param, end - param);
460 } else if (g_str_has_prefix(hdr, "targetname=\"")) {
461 g_free(auth->target);
462 auth->target = g_strndup(param, end - param);
463 } else if (g_str_has_prefix(hdr, "version=")) {
464 auth->version = atoi(param);
467 /* skip to next parameter */
468 while ((*end == '"') || (*end == ',') || (*end == ' '))
469 end++;
470 hdr = end;
473 return;
476 static void sign_outgoing_message(struct sipe_core_private *sipe_private,
477 struct sipmsg *msg)
479 struct sip_transport *transport = sipe_private->transport;
480 gchar *buf;
482 if (transport->registrar.type == SIPE_AUTHENTICATION_TYPE_UNSET) {
483 return;
486 sipe_make_signature(sipe_private, msg);
488 buf = auth_header(sipe_private, &transport->registrar, msg);
489 if (buf) {
490 sipmsg_add_header_now(msg, "Authorization", buf);
491 g_free(buf);
495 static const gchar *sip_transport_user_agent(struct sipe_core_private *sipe_private)
497 struct sip_transport *transport = sipe_private->transport;
499 if (!transport->user_agent) {
500 const gchar *useragent = sipe_backend_setting(SIPE_CORE_PUBLIC,
501 SIPE_SETTING_USER_AGENT);
502 if (is_empty(useragent)) {
503 /*@TODO: better approach to define _user_ OS, it's version and host architecture */
504 /* ref: lzodefs.h */
505 #if defined(__linux__) || defined(__linux) || defined(__LINUX__)
506 #define SIPE_TARGET_PLATFORM "linux"
507 #elif defined(__NetBSD__) ||defined( __OpenBSD__) || defined(__FreeBSD__)
508 #define SIPE_TARGET_PLATFORM "bsd"
509 #elif defined(__APPLE__) || defined(__MACOS__)
510 #define SIPE_TARGET_PLATFORM "macosx"
511 #elif defined(_AIX) || defined(__AIX__) || defined(__aix__)
512 #define SIPE_TARGET_PLATFORM "aix"
513 #elif defined(__solaris__) || defined(__sun)
514 #define SIPE_TARGET_PLATFORM "sun"
515 #elif defined(_WIN32)
516 #define SIPE_TARGET_PLATFORM "win"
517 #elif defined(__CYGWIN__)
518 #define SIPE_TARGET_PLATFORM "cygwin"
519 #elif defined(__hpux__)
520 #define SIPE_TARGET_PLATFORM "hpux"
521 #elif defined(__sgi__)
522 #define SIPE_TARGET_PLATFORM "irix"
523 #else
524 #define SIPE_TARGET_PLATFORM "unknown"
525 #endif
527 #if defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)
528 #define SIPE_TARGET_ARCH "x86_64"
529 #elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386)
530 #define SIPE_TARGET_ARCH "i386"
531 #elif defined(__ppc64__)
532 #define SIPE_TARGET_ARCH "ppc64"
533 #elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR)
534 #define SIPE_TARGET_ARCH "ppc"
535 #elif defined(__hppa__) || defined(__hppa)
536 #define SIPE_TARGET_ARCH "hppa"
537 #elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000)
538 #define SIPE_TARGET_ARCH "mips"
539 #elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x)
540 #define SIPE_TARGET_ARCH "s390"
541 #elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8)
542 #define SIPE_TARGET_ARCH "sparc"
543 #elif defined(__arm__)
544 #define SIPE_TARGET_ARCH "arm"
545 #else
546 #define SIPE_TARGET_ARCH "other"
547 #endif
548 gchar *backend = sipe_backend_version();
549 transport->user_agent = g_strdup_printf("%s Sipe/" PACKAGE_VERSION " (" SIPE_TARGET_PLATFORM "-" SIPE_TARGET_ARCH "; %s)",
550 backend,
551 transport->server_version ? transport->server_version : "");
552 g_free(backend);
553 } else {
554 transport->user_agent = g_strdup(useragent);
557 return(transport->user_agent);
561 * NOTE: Do *NOT* call sipe_backend_transport_message(...) directly!
563 * All SIP messages must pass through this function in order to update
564 * the timestamp for keepalive tracking.
566 static void send_sip_message(struct sip_transport *transport,
567 const gchar *string)
569 sipe_utils_message_debug("SIP", string, NULL, TRUE);
570 transport->last_message = time(NULL);
571 sipe_backend_transport_message(transport->connection, string);
574 static void start_keepalive_timer(struct sipe_core_private *sipe_private,
575 guint seconds);
576 static void keepalive_timeout(struct sipe_core_private *sipe_private,
577 SIPE_UNUSED_PARAMETER gpointer data)
579 struct sip_transport *transport = sipe_private->transport;
580 if (transport) {
581 guint since_last = time(NULL) - transport->last_message;
582 guint restart = transport->keepalive_timeout;
583 if (since_last >= restart) {
584 SIPE_DEBUG_INFO("keepalive_timeout: expired %d", restart);
585 send_sip_message(transport, "\r\n\r\n");
586 } else {
587 /* timeout not reached since last message -> reschedule */
588 restart -= since_last;
590 start_keepalive_timer(sipe_private, restart);
594 static void start_keepalive_timer(struct sipe_core_private *sipe_private,
595 guint seconds)
597 sipe_schedule_seconds(sipe_private,
598 "<+keepalive-timeout>",
599 NULL,
600 seconds,
601 keepalive_timeout,
602 NULL);
605 void sip_transport_response(struct sipe_core_private *sipe_private,
606 struct sipmsg *msg,
607 guint code,
608 const char *text,
609 const char *body)
611 gchar *name;
612 gchar *value;
613 GString *outstr = g_string_new("");
614 gchar *contact;
615 GSList *tmp;
616 static const gchar *keepers[] = { "To", "From", "Call-ID", "CSeq", "Via", "Record-Route", NULL };
618 /* Can return NULL! */
619 contact = get_contact(sipe_private);
620 if (contact) {
621 sipmsg_add_header(msg, "Contact", contact);
622 g_free(contact);
625 if (body) {
626 gchar *len = g_strdup_printf("%" G_GSIZE_FORMAT , (gsize) strlen(body));
627 sipmsg_add_header(msg, "Content-Length", len);
628 g_free(len);
629 } else {
630 sipmsg_add_header(msg, "Content-Length", "0");
633 sipmsg_add_header(msg, "User-Agent", sip_transport_user_agent(sipe_private));
635 msg->response = code;
637 sipmsg_strip_headers(msg, keepers);
638 sipmsg_merge_new_headers(msg);
639 sign_outgoing_message(sipe_private, msg);
641 g_string_append_printf(outstr, "SIP/2.0 %d %s\r\n", code, text);
642 tmp = msg->headers;
643 while (tmp) {
644 name = ((struct sipnameval*) (tmp->data))->name;
645 value = ((struct sipnameval*) (tmp->data))->value;
647 g_string_append_printf(outstr, "%s: %s\r\n", name, value);
648 tmp = g_slist_next(tmp);
650 g_string_append_printf(outstr, "\r\n%s", body ? body : "");
651 send_sip_message(sipe_private->transport, outstr->str);
652 g_string_free(outstr, TRUE);
655 static void transactions_remove(struct sipe_core_private *sipe_private,
656 struct transaction *trans)
658 struct sip_transport *transport = sipe_private->transport;
659 if (transport->transactions) {
660 transport->transactions = g_slist_remove(transport->transactions,
661 trans);
662 SIPE_DEBUG_INFO("SIP transactions count:%d after removal", g_slist_length(transport->transactions));
664 if (trans->msg) sipmsg_free(trans->msg);
665 if (trans->payload) {
666 if (trans->payload->destroy)
667 (*trans->payload->destroy)(trans->payload->data);
668 g_free(trans->payload);
670 g_free(trans->key);
671 if (trans->timeout_key) {
672 sipe_schedule_cancel(sipe_private, trans->timeout_key);
673 g_free(trans->timeout_key);
675 g_free(trans);
679 static struct transaction *transactions_find(struct sip_transport *transport,
680 struct sipmsg *msg)
682 GSList *transactions = transport->transactions;
683 const gchar *call_id = sipmsg_find_header(msg, "Call-ID");
684 const gchar *cseq = sipmsg_find_header(msg, "CSeq");
685 gchar *key;
687 if (!call_id || !cseq) {
688 SIPE_DEBUG_ERROR_NOFORMAT("transaction_find: no Call-ID or CSeq!");
689 return NULL;
692 key = g_strdup_printf("<%s><%s>", call_id, cseq);
693 while (transactions) {
694 struct transaction *trans = transactions->data;
695 if (!g_ascii_strcasecmp(trans->key, key)) {
696 g_free(key);
697 return trans;
699 transactions = transactions->next;
701 g_free(key);
703 return NULL;
706 static void transaction_timeout_cb(struct sipe_core_private *sipe_private,
707 gpointer data)
709 struct transaction *trans = data;
710 (trans->timeout_callback)(sipe_private, trans->msg, trans);
711 transactions_remove(sipe_private, trans);
714 struct transaction *sip_transport_request_timeout(struct sipe_core_private *sipe_private,
715 const gchar *method,
716 const gchar *url,
717 const gchar *to,
718 const gchar *addheaders,
719 const gchar *body,
720 struct sip_dialog *dialog,
721 TransCallback callback,
722 guint timeout,
723 TransCallback timeout_callback)
725 struct sip_transport *transport = sipe_private->transport;
726 char *buf;
727 struct sipmsg *msg;
728 gchar *ourtag = dialog && dialog->ourtag ? g_strdup(dialog->ourtag) : NULL;
729 gchar *theirtag = dialog && dialog->theirtag ? g_strdup(dialog->theirtag) : NULL;
730 gchar *theirepid = dialog && dialog->theirepid ? g_strdup(dialog->theirepid) : NULL;
731 gchar *callid = dialog && dialog->callid ? g_strdup(dialog->callid) : gencallid();
732 gchar *branch = dialog && dialog->callid ? NULL : genbranch();
733 gchar *route = g_strdup("");
734 const gchar *epid = transport->epid;
735 int cseq = dialog ? ++dialog->cseq : 1 /* as Call-Id is new in this case */;
736 struct transaction *trans = NULL;
738 if (dialog && dialog->routes)
740 GSList *iter = dialog->routes;
742 while(iter)
744 char *tmp = route;
745 route = g_strdup_printf("%sRoute: %s\r\n", route, (char *)iter->data);
746 g_free(tmp);
747 iter = g_slist_next(iter);
751 if (!ourtag && !dialog) {
752 ourtag = gentag();
755 if (sipe_strequal(method, "REGISTER")) {
756 if (sipe_private->register_callid) {
757 g_free(callid);
758 callid = g_strdup(sipe_private->register_callid);
759 } else {
760 sipe_private->register_callid = g_strdup(callid);
762 cseq = ++transport->cseq;
765 buf = g_strdup_printf("%s %s SIP/2.0\r\n"
766 "Via: SIP/2.0/%s %s:%d%s%s\r\n"
767 "From: <sip:%s>%s%s;epid=%s\r\n"
768 "To: <%s>%s%s%s%s\r\n"
769 "Max-Forwards: 70\r\n"
770 "CSeq: %d %s\r\n"
771 "User-Agent: %s\r\n"
772 "Call-ID: %s\r\n"
773 "%s%s"
774 "Content-Length: %" G_GSIZE_FORMAT "\r\n\r\n%s",
775 method,
776 dialog && dialog->request ? dialog->request : url,
777 TRANSPORT_DESCRIPTOR,
778 transport->ip_address,
779 transport->connection->client_port,
780 branch ? ";branch=" : "",
781 branch ? branch : "",
782 sipe_private->username,
783 ourtag ? ";tag=" : "",
784 ourtag ? ourtag : "",
785 epid,
787 theirtag ? ";tag=" : "",
788 theirtag ? theirtag : "",
789 theirepid ? ";epid=" : "",
790 theirepid ? theirepid : "",
791 cseq,
792 method,
793 sip_transport_user_agent(sipe_private),
794 callid,
795 route,
796 addheaders ? addheaders : "",
797 body ? (gsize) strlen(body) : 0,
798 body ? body : "");
801 //printf ("parsing msg buf:\n%s\n\n", buf);
802 msg = sipmsg_parse_msg(buf);
804 g_free(buf);
805 g_free(ourtag);
806 g_free(theirtag);
807 g_free(theirepid);
808 g_free(branch);
809 g_free(route);
811 sign_outgoing_message(sipe_private, msg);
813 /* The authentication scheme is not ready so we can't send the message.
814 This should only happen for REGISTER messages. */
815 if (!transport->auth_incomplete) {
816 buf = sipmsg_to_string(msg);
818 /* add to ongoing transactions */
819 /* ACK isn't supposed to be answered ever. So we do not keep transaction for it. */
820 if (!sipe_strequal(method, "ACK")) {
821 trans = g_new0(struct transaction, 1);
822 trans->callback = callback;
823 trans->msg = msg;
824 trans->key = g_strdup_printf("<%s><%d %s>", callid, cseq, method);
825 if (timeout_callback) {
826 trans->timeout_callback = timeout_callback;
827 trans->timeout_key = g_strdup_printf("<transaction timeout>%s", trans->key);
828 sipe_schedule_seconds(sipe_private,
829 trans->timeout_key,
830 trans,
831 timeout,
832 transaction_timeout_cb,
833 NULL);
835 transport->transactions = g_slist_append(transport->transactions,
836 trans);
837 SIPE_DEBUG_INFO("SIP transactions count:%d after addition", g_slist_length(transport->transactions));
840 send_sip_message(transport, buf);
841 g_free(buf);
844 if (!trans) sipmsg_free(msg);
845 g_free(callid);
846 return trans;
849 struct transaction *sip_transport_request(struct sipe_core_private *sipe_private,
850 const gchar *method,
851 const gchar *url,
852 const gchar *to,
853 const gchar *addheaders,
854 const gchar *body,
855 struct sip_dialog *dialog,
856 TransCallback callback)
858 return sip_transport_request_timeout(sipe_private,
859 method,
860 url,
862 addheaders,
863 body,
864 dialog,
865 callback,
867 NULL);
870 static void sip_transport_simple_request(struct sipe_core_private *sipe_private,
871 const gchar *method,
872 struct sip_dialog *dialog)
874 sip_transport_request(sipe_private,
875 method,
876 dialog->with,
877 dialog->with,
878 NULL,
879 NULL,
880 dialog,
881 NULL);
884 void sip_transport_ack(struct sipe_core_private *sipe_private,
885 struct sip_dialog *dialog)
887 sip_transport_simple_request(sipe_private, "ACK", dialog);
890 void sip_transport_bye(struct sipe_core_private *sipe_private,
891 struct sip_dialog *dialog)
893 sip_transport_simple_request(sipe_private, "BYE", dialog);
896 struct transaction *sip_transport_info(struct sipe_core_private *sipe_private,
897 const gchar *addheaders,
898 const gchar *body,
899 struct sip_dialog *dialog,
900 TransCallback callback)
902 return sip_transport_request(sipe_private,
903 "INFO",
904 dialog->with,
905 dialog->with,
906 addheaders,
907 body,
908 dialog,
909 callback);
912 struct transaction *sip_transport_invite(struct sipe_core_private *sipe_private,
913 const gchar *addheaders,
914 const gchar *body,
915 struct sip_dialog *dialog,
916 TransCallback callback)
918 return sip_transport_request(sipe_private,
919 "INVITE",
920 dialog->with,
921 dialog->with,
922 addheaders,
923 body,
924 dialog,
925 callback);
928 struct transaction *sip_transport_service(struct sipe_core_private *sipe_private,
929 const gchar *uri,
930 const gchar *addheaders,
931 const gchar *body,
932 TransCallback callback)
934 return sip_transport_request(sipe_private,
935 "SERVICE",
936 uri,
937 uri,
938 addheaders,
939 body,
940 NULL,
941 callback);
944 void sip_transport_subscribe(struct sipe_core_private *sipe_private,
945 const gchar *uri,
946 const gchar *addheaders,
947 const gchar *body,
948 struct sip_dialog *dialog,
949 TransCallback callback)
951 sip_transport_request(sipe_private,
952 "SUBSCRIBE",
953 uri,
954 uri,
955 addheaders,
956 body,
957 dialog,
958 callback);
961 void sip_transport_update(struct sipe_core_private *sipe_private,
962 struct sip_dialog *dialog,
963 TransCallback callback)
965 sip_transport_request(sipe_private,
966 "UPDATE",
967 dialog->with,
968 dialog->with,
969 NULL,
970 NULL,
971 dialog,
972 callback);
975 static const gchar *get_auth_header(struct sipe_core_private *sipe_private,
976 guint type,
977 struct sipmsg *msg)
979 struct sip_auth *auth = &sipe_private->transport->registrar;
981 auth->type = type;
982 auth->protocol = auth_type_to_protocol[auth->type];
984 return(sipmsg_find_auth_header(msg, auth->protocol));
987 static void do_register(struct sipe_core_private *sipe_private,
988 gboolean deregister);
990 static void do_reauthenticate_cb(struct sipe_core_private *sipe_private,
991 SIPE_UNUSED_PARAMETER gpointer unused)
993 struct sip_transport *transport = sipe_private->transport;
995 /* register again when security token expires */
996 /* we have to start a new authentication as the security token
997 * is almost expired by sending a not signed REGISTER message */
998 SIPE_LOG_INFO_NOFORMAT("do_reauthenticate_cb: do a full reauthentication");
999 sipe_auth_free(&transport->registrar);
1000 sipe_auth_free(&transport->proxy);
1001 sipe_schedule_cancel(sipe_private, "<registration>");
1002 transport->auth_retry = TRUE;
1003 transport->reregister_set = FALSE;
1004 transport->register_attempt = 0;
1005 do_register(sipe_private, FALSE);
1006 transport->reauthenticate_set = FALSE;
1009 static void sip_transport_default_contact(struct sipe_core_private *sipe_private)
1011 struct sip_transport *transport = sipe_private->transport;
1012 sipe_private->contact = g_strdup_printf("<sip:%s:%d;maddr=%s;transport=%s>;proxy=replace",
1013 sipe_private->username,
1014 transport->connection->client_port,
1015 transport->ip_address,
1016 TRANSPORT_DESCRIPTOR);
1019 static void do_register_cb(struct sipe_core_private *sipe_private,
1020 SIPE_UNUSED_PARAMETER void *unused)
1022 do_register(sipe_private, FALSE);
1025 static void sip_transport_set_reregister(struct sipe_core_private *sipe_private,
1026 int expires)
1028 sipe_schedule_seconds(sipe_private,
1029 "<registration>",
1030 NULL,
1031 expires,
1032 do_register_cb,
1033 NULL);
1036 static void sipe_server_register(struct sipe_core_private *sipe_private,
1037 guint type,
1038 gchar *server_name,
1039 guint server_port);
1041 static gboolean process_register_response(struct sipe_core_private *sipe_private,
1042 struct sipmsg *msg,
1043 SIPE_UNUSED_PARAMETER struct transaction *trans)
1045 struct sip_transport *transport = sipe_private->transport;
1046 const gchar *expires_header;
1047 int expires, i;
1048 GSList *hdr = msg->headers;
1049 struct sipnameval *elem;
1051 expires_header = sipmsg_find_header(msg, "Expires");
1052 expires = expires_header != NULL ? strtol(expires_header, NULL, 10) : 0;
1053 SIPE_DEBUG_INFO("process_register_response: got response to REGISTER; expires = %d", expires);
1055 switch (msg->response) {
1056 case 200:
1057 if (expires) {
1058 const gchar *contact_hdr;
1059 const gchar *auth_hdr;
1060 gchar *gruu = NULL;
1061 gchar *uuid;
1062 gchar *timeout;
1063 const gchar *server_hdr = sipmsg_find_header(msg, "Server");
1065 if (!transport->reregister_set) {
1066 /* Schedule re-register 30 seconds before expiration */
1067 if (expires > 30)
1068 expires -= 30;
1069 sip_transport_set_reregister(sipe_private,
1070 expires);
1071 transport->reregister_set = TRUE;
1074 if (server_hdr && !transport->server_version) {
1075 transport->server_version = g_strdup(server_hdr);
1076 g_free(transport->user_agent);
1077 transport->user_agent = NULL;
1080 auth_hdr = sipmsg_find_auth_header(msg,
1081 transport->registrar.protocol);
1082 if (auth_hdr) {
1083 SIPE_DEBUG_INFO("process_register_response: Auth header: %s", auth_hdr);
1084 fill_auth(auth_hdr, &transport->registrar);
1087 if (!transport->reauthenticate_set) {
1088 /* [MS-SIPAE] Section 3.2.2 Timers
1090 * When the ... authentication handshake completes
1091 * and the SA enters the "established" state, the
1092 * SIP protocol client MUST start an SA expiration
1093 * timer.
1094 * ...
1095 * The expiration timer value is the lesser of
1097 * - Kerberos: the service ticket expiry time
1098 * - TLS-DSK: the certificate expiration time
1100 * and eight hours, further reduced by some buffer
1101 * time.
1102 * ...
1103 * The protocol client MUST choose a sufficient
1104 * buffer time to allow for the ... authentication
1105 * handshake that reestablishes the SA to complete
1106 * ... This value SHOULD be five (5) minutes or
1107 * longer.
1109 guint reauth_timeout = transport->registrar.expires;
1111 SIPE_LOG_INFO_NOFORMAT("process_register_response: authentication handshake completed successfully");
1113 if ((reauth_timeout == 0) ||
1114 (reauth_timeout > 8 * 60 * 60))
1115 reauth_timeout = 8 * 60 * 60;
1116 if (reauth_timeout > 5 * 60)
1117 reauth_timeout -= 5 * 60;
1119 sipe_schedule_seconds(sipe_private,
1120 "<+reauthentication>",
1121 NULL,
1122 reauth_timeout,
1123 do_reauthenticate_cb,
1124 NULL);
1125 transport->reauthenticate_set = TRUE;
1128 uuid = get_uuid(sipe_private);
1130 // There can be multiple Contact headers (one per location where the user is logged in) so
1131 // make sure to only get the one for this uuid
1132 for (i = 0; (contact_hdr = sipmsg_find_header_instance (msg, "Contact", i)); i++) {
1133 gchar * valid_contact = sipmsg_find_part_of_header (contact_hdr, uuid, NULL, NULL);
1134 if (valid_contact) {
1135 gruu = sipmsg_find_part_of_header(contact_hdr, "gruu=\"", "\"", NULL);
1136 //SIPE_DEBUG_INFO("process_register_response: got gruu %s from contact hdr w/ right uuid: %s", gruu, contact_hdr);
1137 g_free(valid_contact);
1138 break;
1139 } else {
1140 //SIPE_DEBUG_INFO("process_register_response: ignoring contact hdr b/c not right uuid: %s", contact_hdr);
1143 g_free(uuid);
1145 g_free(sipe_private->contact);
1146 if(gruu) {
1147 sipe_private->contact = g_strdup_printf("<%s>", gruu);
1148 g_free(gruu);
1149 } else {
1150 //SIPE_DEBUG_INFO_NOFORMAT("process_register_response: didn't find gruu in a Contact hdr");
1151 sip_transport_default_contact(sipe_private);
1153 SIPE_CORE_PRIVATE_FLAG_UNSET(OCS2007);
1154 SIPE_CORE_PRIVATE_FLAG_UNSET(REMOTE_USER);
1155 SIPE_CORE_PRIVATE_FLAG_UNSET(BATCHED_SUPPORT);
1156 SIPE_CORE_PRIVATE_FLAG_UNSET(SFB);
1158 while(hdr)
1160 elem = hdr->data;
1161 if (sipe_strcase_equal(elem->name, "Supported")) {
1162 if (sipe_strcase_equal(elem->value, "msrtc-event-categories")) {
1163 /* We interpret this as OCS2007+ indicator */
1164 SIPE_CORE_PRIVATE_FLAG_SET(OCS2007);
1165 SIPE_LOG_INFO("process_register_response: Supported: %s (indicates OCS2007+)", elem->value);
1167 if (sipe_strcase_equal(elem->value, "adhoclist")) {
1168 SIPE_CORE_PRIVATE_FLAG_SET(BATCHED_SUPPORT);
1169 SIPE_DEBUG_INFO("process_register_response: Supported: %s", elem->value);
1172 if (sipe_strcase_equal(elem->name, "Allow-Events")){
1173 gchar **caps = g_strsplit(elem->value,",",0);
1174 i = 0;
1175 while (caps[i]) {
1176 sipe_private->allowed_events = g_slist_append(sipe_private->allowed_events, g_strdup(caps[i]));
1177 SIPE_DEBUG_INFO("process_register_response: Allow-Events: %s", caps[i]);
1178 i++;
1180 g_strfreev(caps);
1182 if (sipe_strcase_equal(elem->name, "ms-user-logon-data")) {
1183 if (sipe_strcase_equal(elem->value, "RemoteUser")) {
1184 SIPE_CORE_PRIVATE_FLAG_SET(REMOTE_USER);
1185 SIPE_DEBUG_INFO_NOFORMAT("process_register_response: ms-user-logon-data: RemoteUser (connected "
1186 "via Edge Server)");
1189 if (sipe_strcase_equal(elem->name, "Server")) {
1190 /* Server string has format like 'RTC/6.0'.
1191 * We want to check the first digit. */
1192 gchar **parts = g_strsplit_set(elem->value, "/.", 3);
1193 if ((g_strv_length(parts) > 1) && (atoi(parts[1]) >= 6)) {
1194 SIPE_CORE_PRIVATE_FLAG_SET(SFB);
1196 g_strfreev(parts);
1198 hdr = g_slist_next(hdr);
1201 sipe_backend_connection_completed(SIPE_CORE_PUBLIC);
1203 /* rejoin open chats to be able to use them by continue to send messages */
1204 sipe_backend_chat_rejoin_all(SIPE_CORE_PUBLIC);
1206 /* subscriptions, done only once */
1207 if (!transport->subscribed) {
1208 sipe_subscription_self_events(sipe_private);
1209 transport->subscribed = TRUE;
1212 timeout = sipmsg_find_part_of_header(sipmsg_find_header(msg, "ms-keep-alive"),
1213 "timeout=", ";", NULL);
1214 if (timeout != NULL) {
1215 sscanf(timeout, "%u", &transport->keepalive_timeout);
1216 SIPE_DEBUG_INFO("process_register_response: server determined keep alive timeout is %u seconds",
1217 transport->keepalive_timeout);
1218 g_free(timeout);
1221 SIPE_DEBUG_INFO("process_register_response: got 200, removing CSeq: %d", transport->cseq);
1223 break;
1224 case 301:
1226 gchar *redirect = parse_from(sipmsg_find_header(msg, "Contact"));
1228 SIPE_LOG_INFO_NOFORMAT("process_register_response: authentication handshake completed successfully (with redirect)");
1230 if (redirect && (g_ascii_strncasecmp("sip:", redirect, 4) == 0)) {
1231 gchar **parts = g_strsplit(redirect + 4, ";", 0);
1232 gchar **tmp;
1233 gchar *hostname;
1234 int port = 0;
1235 guint transport_type = SIPE_TRANSPORT_TLS;
1236 int i = 1;
1238 tmp = g_strsplit(parts[0], ":", 0);
1239 hostname = g_strdup(tmp[0]);
1240 if (tmp[1]) port = strtoul(tmp[1], NULL, 10);
1241 g_strfreev(tmp);
1243 while (parts[i]) {
1244 tmp = g_strsplit(parts[i], "=", 0);
1245 if (tmp[1]) {
1246 if (g_ascii_strcasecmp("transport", tmp[0]) == 0) {
1247 if (g_ascii_strcasecmp("tcp", tmp[1]) == 0) {
1248 transport_type = SIPE_TRANSPORT_TCP;
1252 g_strfreev(tmp);
1253 i++;
1255 g_strfreev(parts);
1257 /* Close old connection */
1258 sipe_core_connection_cleanup(sipe_private);
1259 /* transport and sipe_private->transport are invalid after this */
1261 /* Create new connection */
1262 sipe_server_register(sipe_private, transport_type, hostname, port);
1263 /* sipe_private->transport has a new value */
1264 SIPE_DEBUG_INFO("process_register_response: redirected to host %s port %d transport %d",
1265 hostname, port, transport_type);
1267 g_free(redirect);
1269 break;
1270 case 401:
1272 const char *auth_hdr = NULL;
1274 SIPE_DEBUG_INFO("process_register_response: REGISTER retries %d", transport->registrar.retries);
1276 if (transport->reauthenticate_set) {
1277 SIPE_DEBUG_ERROR_NOFORMAT("process_register_response: RE-REGISTER rejected, triggering re-authentication");
1278 do_reauthenticate_cb(sipe_private, NULL);
1279 return TRUE;
1282 if (sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
1283 struct sip_auth *auth = &transport->registrar;
1285 /* NTLM is the scheme with lowest priority - don't retry */
1286 if (auth_can_retry(transport, auth)) {
1287 guint failed = auth->type;
1288 SIPE_DEBUG_INFO_NOFORMAT("process_register_response: authentication handshake failed - trying next authentication scheme.");
1289 sipe_auth_free(auth);
1290 auth->type = failed;
1291 } else {
1292 SIPE_LOG_ERROR_NOFORMAT("process_register_response: authentication handshake failed - giving up.");
1293 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1294 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
1295 _("Authentication failed"));
1296 return TRUE;
1300 if (sipe_private->authentication_type == SIPE_AUTHENTICATION_TYPE_AUTOMATIC) {
1301 struct sip_auth *auth = &transport->registrar;
1302 guint try = auth->type;
1304 while (!auth_hdr) {
1306 * Determine next authentication
1307 * scheme in priority order
1309 if (transport->auth_retry)
1310 switch (try) {
1311 case SIPE_AUTHENTICATION_TYPE_UNSET:
1312 try = SIPE_AUTHENTICATION_TYPE_TLS_DSK;
1313 break;
1315 case SIPE_AUTHENTICATION_TYPE_TLS_DSK:
1316 #if defined(HAVE_GSSAPI_GSSAPI_H) || defined(HAVE_SSPI)
1317 try = SIPE_AUTHENTICATION_TYPE_KERBEROS;
1318 break;
1320 case SIPE_AUTHENTICATION_TYPE_KERBEROS:
1321 #endif
1322 try = SIPE_AUTHENTICATION_TYPE_NTLM;
1323 break;
1325 default:
1326 try = SIPE_AUTHENTICATION_TYPE_UNSET;
1327 break;
1330 auth->can_retry = (try != SIPE_AUTHENTICATION_TYPE_UNSET);
1332 if (!auth->can_retry) {
1333 SIPE_DEBUG_INFO_NOFORMAT("process_register_response: no more authentication schemes to try");
1334 break;
1337 auth_hdr = get_auth_header(sipe_private,
1338 try,
1339 msg);
1342 transport->auth_retry = FALSE;
1344 } else
1345 auth_hdr = get_auth_header(sipe_private,
1346 sipe_private->authentication_type,
1347 msg);
1349 if (!auth_hdr) {
1350 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1351 SIPE_CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE,
1352 _("Incompatible authentication scheme chosen"));
1353 return TRUE;
1355 SIPE_DEBUG_INFO("process_register_response: Auth header: %s", auth_hdr);
1356 fill_auth(auth_hdr, &transport->registrar);
1357 transport->reregister_set = FALSE;
1358 transport->register_attempt = 0;
1359 do_register(sipe_private,
1360 sipe_backend_connection_is_disconnecting(SIPE_CORE_PUBLIC));
1362 break;
1363 case 403:
1365 gchar *reason;
1366 gchar *warning;
1367 sipmsg_parse_warning(msg, &reason);
1368 reason = reason ? reason : sipmsg_get_ms_diagnostics_public_reason(msg);
1369 warning = g_strdup_printf(_("You have been rejected by the server: %s"),
1370 reason ? reason : _("no reason given"));
1371 g_free(reason);
1373 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1374 SIPE_CONNECTION_ERROR_INVALID_SETTINGS,
1375 warning);
1376 g_free(warning);
1377 return TRUE;
1379 break;
1380 case 404:
1382 const gchar *diagnostics = sipmsg_find_header(msg, "ms-diagnostics");
1383 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1384 gchar *warning;
1385 warning = g_strdup_printf(_("Not found: %s. Please contact your Administrator"),
1386 diagnostics ? (reason ? reason : _("no reason given")) :
1387 _("SIP is either not enabled for the destination URI or it does not exist"));
1388 g_free(reason);
1390 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1391 SIPE_CONNECTION_ERROR_INVALID_USERNAME,
1392 warning);
1393 g_free(warning);
1394 return TRUE;
1396 break;
1397 case 504: /* Server time-out */
1398 /* first attempt + 5 retries */
1399 if (transport->register_attempt < 6) {
1400 SIPE_DEBUG_INFO("process_register_response: RE-REGISTER timeout on attempt %d, retrying later",
1401 transport->register_attempt);
1402 sip_transport_set_reregister(sipe_private, 60);
1403 return TRUE;
1405 /* FALLTHROUGH */
1406 case 503:
1408 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1409 gchar *warning;
1410 warning = g_strdup_printf(_("Service unavailable: %s"), reason ? reason : _("no reason given"));
1411 g_free(reason);
1413 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1414 SIPE_CONNECTION_ERROR_NETWORK,
1415 warning);
1416 g_free(warning);
1417 return TRUE;
1419 break;
1421 return TRUE;
1424 static gboolean register_response_timeout(struct sipe_core_private *sipe_private,
1425 SIPE_UNUSED_PARAMETER struct sipmsg *msg,
1426 SIPE_UNUSED_PARAMETER struct transaction *trans)
1428 struct sip_transport *transport = sipe_private->transport;
1429 if (transport->register_attempt < 6) {
1430 SIPE_DEBUG_INFO("register_response_timeout: no answer to attempt %d, retrying",
1431 transport->register_attempt);
1432 do_register(sipe_private, FALSE);
1433 } else {
1434 gchar *warning = g_strdup_printf(_("Service unavailable: %s"), _("no reason given"));
1435 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1436 SIPE_CONNECTION_ERROR_NETWORK,
1437 warning);
1438 g_free(warning);
1440 return TRUE;
1443 static void do_register(struct sipe_core_private *sipe_private,
1444 gboolean deregister)
1446 struct sip_transport *transport = sipe_private->transport;
1447 char *uri;
1448 char *to;
1449 char *hdr;
1450 char *uuid;
1452 if (!sipe_private->public.sip_domain) return;
1454 if (!deregister) {
1455 if (transport->reregister_set) {
1456 transport->reregister_set = FALSE;
1457 transport->register_attempt = 1;
1458 } else {
1459 transport->register_attempt++;
1463 transport->deregister = deregister;
1464 transport->auth_incomplete = FALSE;
1466 uuid = get_uuid(sipe_private);
1467 hdr = g_strdup_printf("Contact: <sip:%s:%d;transport=%s;ms-opaque=d3470f2e1d>;methods=\"INVITE, MESSAGE, INFO, SUBSCRIBE, OPTIONS, BYE, CANCEL, NOTIFY, ACK, REFER, BENOTIFY\";proxy=replace;+sip.instance=\"<urn:uuid:%s>\"\r\n"
1468 "Supported: gruu-10, adhoclist, msrtc-event-categories, com.microsoft.msrtc.presence\r\n"
1469 "Event: registration\r\n"
1470 "Allow-Events: presence\r\n"
1471 "ms-keep-alive: UAC;hop-hop=yes\r\n"
1472 "%s",
1473 transport->ip_address,
1474 transport->connection->client_port,
1475 TRANSPORT_DESCRIPTOR,
1476 uuid,
1477 deregister ? "Expires: 0\r\n" : "");
1478 g_free(uuid);
1480 uri = sip_uri_from_name(sipe_private->public.sip_domain);
1481 to = sip_uri_self(sipe_private);
1482 sip_transport_request_timeout(sipe_private,
1483 "REGISTER",
1484 uri,
1486 hdr,
1488 NULL,
1489 process_register_response,
1491 deregister ? NULL : register_response_timeout);
1492 g_free(to);
1493 g_free(uri);
1494 g_free(hdr);
1496 if (deregister) {
1497 /* Make sure that all messages are pushed to the server
1498 before the connection gets shut down */
1499 SIPE_LOG_INFO_NOFORMAT("De-register from server. Flushing outstanding messages.");
1500 sipe_backend_transport_flush(transport->connection);
1504 void sip_transport_deregister(struct sipe_core_private *sipe_private)
1506 do_register(sipe_private, TRUE);
1509 void sip_transport_disconnect(struct sipe_core_private *sipe_private)
1511 struct sip_transport *transport = sipe_private->transport;
1513 /* transport can be NULL during connection setup */
1514 if (transport) {
1515 SIPE_LOG_INFO("sip_transport_disconnect: dropping connection '%s:%u'",
1516 transport->server_name, transport->server_port);
1518 sipe_backend_transport_disconnect(transport->connection);
1520 sipe_auth_free(&transport->registrar);
1521 sipe_auth_free(&transport->proxy);
1523 g_free(transport->server_name);
1524 g_free(transport->server_version);
1525 g_free(transport->ip_address);
1526 g_free(transport->epid);
1527 g_free(transport->user_agent);
1529 while (transport->transactions)
1530 transactions_remove(sipe_private,
1531 transport->transactions->data);
1533 g_free(transport);
1536 sipe_private->transport = NULL;
1537 sipe_private->service_data = NULL;
1538 sipe_private->address_data = NULL;
1540 sipe_schedule_cancel(sipe_private, "<+keepalive-timeout>");
1542 if (sipe_private->dns_query)
1543 sipe_backend_dns_query_cancel(sipe_private->dns_query);
1547 void sip_transport_authentication_completed(struct sipe_core_private *sipe_private)
1549 do_reauthenticate_cb(sipe_private, NULL);
1552 guint sip_transport_port(struct sipe_core_private *sipe_private)
1554 return sipe_private->transport->server_port;
1557 static void process_input_message(struct sipe_core_private *sipe_private,
1558 struct sipmsg *msg)
1560 struct sip_transport *transport = sipe_private->transport;
1561 gboolean notfound = FALSE;
1562 const char *method = msg->method ? msg->method : "NOT FOUND";
1564 SIPE_DEBUG_INFO("process_input_message: msg->response(%d),msg->method(%s)",
1565 msg->response, method);
1567 if (msg->response == 0) { /* request */
1568 if (sipe_strequal(method, "MESSAGE")) {
1569 process_incoming_message(sipe_private, msg);
1570 } else if (sipe_strequal(method, "NOTIFY")) {
1571 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_notify");
1572 process_incoming_notify(sipe_private, msg);
1573 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1574 } else if (sipe_strequal(method, "BENOTIFY")) {
1575 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_benotify");
1576 process_incoming_notify(sipe_private, msg);
1577 } else if (sipe_strequal(method, "INVITE")) {
1578 process_incoming_invite(sipe_private, msg);
1579 } else if (sipe_strequal(method, "REFER")) {
1580 process_incoming_refer(sipe_private, msg);
1581 } else if (sipe_strequal(method, "OPTIONS")) {
1582 process_incoming_options(sipe_private, msg);
1583 } else if (sipe_strequal(method, "INFO")) {
1584 process_incoming_info(sipe_private, msg);
1585 } else if (sipe_strequal(method, "ACK")) {
1586 /* ACK's don't need any response */
1587 } else if (sipe_strequal(method, "PRACK")) {
1588 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1589 } else if (sipe_strequal(method, "SUBSCRIBE")) {
1590 /* LCS 2005 sends us these - just respond 200 OK */
1591 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1592 } else if (sipe_strequal(method, "CANCEL")) {
1593 process_incoming_cancel(sipe_private, msg);
1594 } else if (sipe_strequal(method, "BYE")) {
1595 process_incoming_bye(sipe_private, msg);
1596 } else {
1597 sip_transport_response(sipe_private, msg, 501, "Not implemented", NULL);
1598 notfound = TRUE;
1601 } else { /* response */
1602 struct transaction *trans = transactions_find(transport, msg);
1603 if (trans) {
1604 if (msg->response < 200) {
1605 /* ignore provisional response */
1606 SIPE_DEBUG_INFO("process_input_message: got provisional (%d) response, ignoring", msg->response);
1608 /* Transaction not yet completed */
1609 trans = NULL;
1611 } else if (msg->response == 401) { /* Unauthorized */
1613 if (sipe_strequal(trans->msg->method, "REGISTER")) {
1614 /* Expected response during authentication handshake */
1615 transport->registrar.retries++;
1616 SIPE_DEBUG_INFO("process_input_message: RE-REGISTER CSeq: %d", transport->cseq);
1617 } else {
1618 gchar *resend;
1620 /* Are we registered? */
1621 if (transport->reregister_set) {
1622 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Retrying with new authentication.");
1623 sipmsg_remove_header_now(trans->msg, "Authorization");
1624 sign_outgoing_message(sipe_private,
1625 trans->msg);
1626 } else {
1628 * We don't have a valid authentication at the moment.
1629 * Resend message unchanged. It will be rejected again
1630 * and hopefully by then we have a valid authentication.
1632 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Bouncing...");
1635 /* Resend request */
1636 resend = sipmsg_to_string(trans->msg);
1637 send_sip_message(sipe_private->transport, resend);
1638 g_free(resend);
1640 /* Transaction not yet completed */
1641 trans = NULL;
1644 } else if (msg->response == 407) { /* Proxy Authentication Required */
1646 if (transport->proxy.retries++ <= 30) {
1647 const gchar *proxy_hdr = sipmsg_find_header(msg, "Proxy-Authenticate");
1649 if (proxy_hdr) {
1650 gchar *auth = NULL;
1652 if (!g_ascii_strncasecmp(proxy_hdr, "Digest", 6)) {
1653 auth = sip_sec_digest_authorization(sipe_private,
1654 proxy_hdr + 7,
1655 msg->method,
1656 msg->target);
1657 } else {
1658 guint i;
1660 transport->proxy.type = SIPE_AUTHENTICATION_TYPE_UNSET;
1661 for (i = 0; i < AUTH_PROTOCOLS; i++) {
1662 const gchar *protocol = auth_type_to_protocol[i];
1663 if (protocol &&
1664 !g_ascii_strncasecmp(proxy_hdr, protocol, strlen(protocol))) {
1665 SIPE_DEBUG_INFO("process_input_message: proxy authentication scheme '%s'", protocol);
1666 transport->proxy.type = i;
1667 transport->proxy.protocol = protocol;
1668 fill_auth(proxy_hdr, &transport->proxy);
1669 auth = auth_header(sipe_private, &transport->proxy, trans->msg);
1670 break;
1675 if (auth) {
1676 gchar *resend;
1678 /* replace old proxy authentication with new one */
1679 sipmsg_remove_header_now(trans->msg, "Proxy-Authorization");
1680 sipmsg_add_header_now(trans->msg, "Proxy-Authorization", auth);
1681 g_free(auth);
1683 /* resend request with proxy authentication */
1684 resend = sipmsg_to_string(trans->msg);
1685 send_sip_message(sipe_private->transport, resend);
1686 g_free(resend);
1688 /* Transaction not yet completed */
1689 trans = NULL;
1691 } else
1692 SIPE_DEBUG_ERROR_NOFORMAT("process_input_message: can't generate proxy authentication. Giving up.");
1693 } else
1694 SIPE_DEBUG_ERROR_NOFORMAT("process_input_message: 407 response without 'Proxy-Authenticate' header. Giving up.");
1695 } else
1696 SIPE_DEBUG_ERROR_NOFORMAT("process_input_message: too many proxy authentication retries. Giving up.");
1698 } else {
1699 transport->registrar.retries = 0;
1700 transport->proxy.retries = 0;
1703 /* Is transaction completed? */
1704 if (trans) {
1705 if (trans->callback) {
1706 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: we have a transaction callback");
1707 /* call the callback to process response */
1708 (trans->callback)(sipe_private, msg, trans);
1709 /* transport && trans no longer valid after redirect */
1713 * Redirect case: sipe_private->transport is
1714 * the new transport with empty queue
1716 if (sipe_private->transport->transactions) {
1717 SIPE_DEBUG_INFO("process_input_message: removing CSeq %d", transport->cseq);
1718 transactions_remove(sipe_private, trans);
1721 } else {
1722 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: received response to unknown transaction");
1723 notfound = TRUE;
1727 if (notfound) {
1728 SIPE_DEBUG_INFO("received a unknown sip message with method %s and response %d", method, msg->response);
1732 static void sip_transport_input(struct sipe_transport_connection *conn)
1734 struct sipe_core_private *sipe_private = conn->user_data;
1735 struct sip_transport *transport = sipe_private->transport;
1736 gchar *cur = conn->buffer;
1738 /* according to the RFC remove CRLF at the beginning */
1739 while (*cur == '\r' || *cur == '\n') {
1740 cur++;
1742 if (cur != conn->buffer)
1743 sipe_utils_shrink_buffer(conn, cur);
1745 /* Received a full Header? */
1746 transport->processing_input = TRUE;
1747 while (transport->processing_input &&
1748 ((cur = strstr(conn->buffer, "\r\n\r\n")) != NULL)) {
1749 struct sipmsg *msg;
1750 guint remainder;
1752 cur += 2;
1753 cur[0] = '\0';
1754 msg = sipmsg_parse_header(conn->buffer);
1756 cur += 2;
1757 remainder = conn->buffer_used - (cur - conn->buffer);
1758 if (msg && remainder >= (guint) msg->bodylen) {
1759 char *dummy = g_malloc(msg->bodylen + 1);
1760 memcpy(dummy, cur, msg->bodylen);
1761 dummy[msg->bodylen] = '\0';
1762 msg->body = dummy;
1763 cur += msg->bodylen;
1764 sipe_utils_message_debug("SIP",
1765 conn->buffer,
1766 msg->body,
1767 FALSE);
1768 sipe_utils_shrink_buffer(conn, cur);
1769 } else {
1770 if (msg) {
1771 SIPE_DEBUG_INFO("sipe_transport_input: body too short (%d < %d, strlen %d) - ignoring message", remainder, msg->bodylen, (int)strlen(conn->buffer));
1772 sipmsg_free(msg);
1775 /* restore header for next try */
1776 cur[-2] = '\r';
1777 return;
1780 /* Fatal header parse error? */
1781 if (msg->response == SIPMSG_RESPONSE_FATAL_ERROR) {
1782 /* can't proceed -> drop connection */
1783 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1784 SIPE_CONNECTION_ERROR_NETWORK,
1785 _("Corrupted message received"));
1786 transport->processing_input = FALSE;
1788 /* Verify the signature before processing it */
1789 } else if (sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
1790 struct sipmsg_breakdown msgbd;
1791 gchar *signature_input_str;
1792 gchar *rspauth;
1793 msgbd.msg = msg;
1794 sipmsg_breakdown_parse(&msgbd, transport->registrar.realm, transport->registrar.target,
1795 transport->registrar.protocol);
1796 signature_input_str = sipmsg_breakdown_get_string(transport->registrar.version, &msgbd);
1798 rspauth = sipmsg_find_part_of_header(sipmsg_find_header(msg, "Authentication-Info"), "rspauth=\"", "\"", NULL);
1800 if (rspauth != NULL) {
1801 if (sip_sec_verify_signature(transport->registrar.gssapi_context, signature_input_str, rspauth)) {
1802 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message validated");
1803 process_input_message(sipe_private, msg);
1804 /* transport is invalid after redirect */
1805 } else {
1806 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message is invalid.");
1807 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1808 SIPE_CONNECTION_ERROR_NETWORK,
1809 _("Invalid message signature received"));
1810 transport->processing_input = FALSE;
1812 } else if ((msg->response == 401) ||
1813 sipe_strequal(msg->method, "REGISTER")) {
1814 /* a) Retry non-REGISTER requests with updated authentication */
1815 /* b) We must always process REGISTER responses */
1816 process_input_message(sipe_private, msg);
1817 } else {
1818 /* OCS sends provisional messages that are *not* signed */
1819 if (msg->response >= 200) {
1820 /* We are not calling process_input_message(),
1821 so we need to drop the transaction here. */
1822 struct transaction *trans = transactions_find(transport, msg);
1823 if (trans) transactions_remove(sipe_private, trans);
1825 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: message without authentication data - ignoring");
1827 g_free(signature_input_str);
1829 g_free(rspauth);
1830 sipmsg_breakdown_free(&msgbd);
1831 } else {
1832 process_input_message(sipe_private, msg);
1835 sipmsg_free(msg);
1837 /* Redirect: old content of "transport" & "conn" is no longer valid */
1838 transport = sipe_private->transport;
1839 conn = transport->connection;
1843 static void sip_transport_connected(struct sipe_transport_connection *conn)
1845 struct sipe_core_private *sipe_private = conn->user_data;
1846 struct sip_transport *transport = sipe_private->transport;
1847 gchar *self_sip_uri = sip_uri_self(sipe_private);
1849 SIPE_LOG_INFO("sip_transport_connected: %s:%u",
1850 transport->server_name, transport->server_port);
1852 while (sipe_private->lync_autodiscover_servers)
1853 sipe_private->lync_autodiscover_servers =
1854 sipe_lync_autodiscover_pop(sipe_private->lync_autodiscover_servers);
1856 sipe_private->service_data = NULL;
1857 sipe_private->address_data = NULL;
1860 * Initial keepalive timeout during REGISTER phase
1862 * NOTE: 60 seconds is a guess. Needs more testing!
1864 transport->keepalive_timeout = 60;
1865 start_keepalive_timer(sipe_private, transport->keepalive_timeout);
1867 transport->ip_address = sipe_backend_transport_ip_address(conn);
1868 transport->epid = sipe_get_epid(self_sip_uri,
1869 g_get_host_name(),
1870 transport->ip_address);
1871 g_free(self_sip_uri);
1873 do_register(sipe_private, FALSE);
1876 static void resolve_next_lync(struct sipe_core_private *sipe_private);
1877 static void resolve_next_service(struct sipe_core_private *sipe_private,
1878 const struct sip_service_data *start);
1879 static void resolve_next_address(struct sipe_core_private *sipe_private,
1880 gboolean initial);
1881 static void sip_transport_error(struct sipe_transport_connection *conn,
1882 const gchar *msg)
1884 struct sipe_core_private *sipe_private = conn->user_data;
1886 /* This failed attempt was based on a Lync Autodiscover result */
1887 if (sipe_private->lync_autodiscover_servers) {
1888 resolve_next_lync(sipe_private);
1889 /* This failed attempt was based on a DNS SRV record */
1890 } else if (sipe_private->service_data) {
1891 resolve_next_service(sipe_private, NULL);
1892 /* This failed attempt was based on a DNS A record */
1893 } else if (sipe_private->address_data) {
1894 resolve_next_address(sipe_private, FALSE);
1895 } else {
1896 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1897 SIPE_CONNECTION_ERROR_NETWORK,
1898 msg);
1902 /* server_name must be g_alloc()'ed */
1903 static void sipe_server_register(struct sipe_core_private *sipe_private,
1904 guint type,
1905 gchar *server_name,
1906 guint server_port)
1908 sipe_connect_setup setup = {
1909 type,
1910 server_name,
1911 (server_port != 0) ? server_port :
1912 (type == SIPE_TRANSPORT_TLS) ? 5061 : 5060,
1913 sipe_private,
1914 sip_transport_connected,
1915 sip_transport_input,
1916 sip_transport_error
1918 struct sip_transport *transport = g_new0(struct sip_transport, 1);
1920 transport->auth_retry = TRUE;
1921 transport->server_name = server_name;
1922 transport->server_port = setup.server_port;
1923 transport->connection = sipe_backend_transport_connect(SIPE_CORE_PUBLIC,
1924 &setup);
1925 sipe_private->transport = transport;
1928 struct sip_service_data {
1929 const char *protocol;
1930 const char *transport;
1931 guint type;
1935 * Autodiscover using DNS SRV records. See RFC2782/3263
1937 * Service list for AUTO
1939 static const struct sip_service_data service_autodetect[] = {
1940 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1941 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1942 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1943 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1944 { NULL, NULL, 0 }
1947 /* Service list for SSL/TLS */
1948 static const struct sip_service_data service_tls[] = {
1949 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1950 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1951 { NULL, NULL, 0 }
1954 /* Service list for TCP */
1955 static const struct sip_service_data service_tcp[] = {
1956 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1957 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1958 { NULL, NULL, 0 }
1961 static const struct sip_service_data *services[] = {
1962 service_autodetect, /* SIPE_TRANSPORT_AUTO */
1963 service_tls, /* SIPE_TRANSPORT_TLS */
1964 service_tcp /* SIPE_TRANSPORT_TCP */
1967 struct sip_address_data {
1968 const char *prefix;
1969 guint port;
1973 * Autodiscover using DNS A records. This is an extension addded
1974 * by Microsoft. See http://support.microsoft.com/kb/2619522
1976 static const struct sip_address_data addresses[] = {
1977 { "sipinternal", 5061 },
1978 { "sipexternal", 443 },
1980 * Our implementation supports only one port per host name. If the host name
1981 * resolves OK, we abort the search and try to connect. If we would know if we
1982 * are trying to connect from "Intranet" or "Internet" then we could choose
1983 * between those two ports.
1985 * We drop port 5061 in order to cover the "Internet" case.
1987 * { "sip", 5061 },
1989 { "sip", 443 },
1990 { NULL, 0 }
1993 static void sipe_core_dns_resolved(struct sipe_core_public *sipe_public,
1994 const gchar *hostname, guint port)
1996 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
1997 gboolean service = sipe_private->service_data != NULL;
1999 sipe_private->dns_query = NULL;
2001 if (hostname) {
2002 gchar *host;
2003 guint type;
2005 if (service) {
2006 host = g_strdup(hostname);
2007 type = sipe_private->service_data->type;
2008 } else {
2009 /* DNS A resolver returns an IP address */
2010 host = g_strdup_printf("%s.%s",
2011 sipe_private->address_data->prefix,
2012 sipe_private->public.sip_domain);
2013 port = sipe_private->address_data->port;
2014 type = sipe_private->transport_type;
2015 if (type == SIPE_TRANSPORT_AUTO)
2016 type = SIPE_TRANSPORT_TLS;
2019 SIPE_DEBUG_INFO("sipe_core_dns_resolved - %s hostname: %s port: %d",
2020 service ? "SRV" : "A", hostname, port);
2021 sipe_server_register(sipe_private, type, host, port);
2022 } else {
2023 if (service)
2024 resolve_next_service(SIPE_CORE_PRIVATE, NULL);
2025 else
2026 resolve_next_address(SIPE_CORE_PRIVATE, FALSE);
2030 static void resolve_next_lync(struct sipe_core_private *sipe_private)
2032 struct sipe_lync_autodiscover_data *lync_data = sipe_private->lync_autodiscover_servers->data;
2033 guint type = sipe_private->transport_type;
2035 if (lync_data) {
2036 /* Try to connect to next server on the list */
2037 if (type == SIPE_TRANSPORT_AUTO)
2038 type = SIPE_TRANSPORT_TLS;
2040 sipe_server_register(sipe_private,
2041 type,
2042 g_strdup(lync_data->server),
2043 lync_data->port);
2045 } else {
2046 /* We tried all servers -> try DNS SRV next */
2047 SIPE_LOG_INFO_NOFORMAT("no Lync Autodiscover servers found; trying SRV records next");
2048 resolve_next_service(sipe_private, services[type]);
2051 sipe_private->lync_autodiscover_servers =
2052 sipe_lync_autodiscover_pop(sipe_private->lync_autodiscover_servers);
2055 static void resolve_next_service(struct sipe_core_private *sipe_private,
2056 const struct sip_service_data *start)
2058 if (start) {
2059 sipe_private->service_data = start;
2060 } else {
2061 sipe_private->service_data++;
2062 if (sipe_private->service_data->protocol == NULL) {
2064 /* We tried all services */
2065 sipe_private->service_data = NULL;
2067 /* Try A records list next */
2068 SIPE_LOG_INFO_NOFORMAT("no SRV records found; trying A records next");
2069 resolve_next_address(sipe_private, TRUE);
2070 return;
2074 /* Try to resolve next service */
2075 sipe_private->dns_query = sipe_backend_dns_query_srv(
2076 SIPE_CORE_PUBLIC,
2077 sipe_private->service_data->protocol,
2078 sipe_private->service_data->transport,
2079 sipe_private->public.sip_domain,
2080 (sipe_dns_resolved_cb) sipe_core_dns_resolved,
2081 SIPE_CORE_PUBLIC);
2084 static void resolve_next_address(struct sipe_core_private *sipe_private,
2085 gboolean initial)
2087 gchar *hostname;
2089 if (initial) {
2090 sipe_private->address_data = addresses;
2091 } else {
2092 sipe_private->address_data++;
2093 if (sipe_private->address_data->prefix == NULL) {
2094 guint type = sipe_private->transport_type;
2096 /* We tried all addresss */
2097 sipe_private->address_data = NULL;
2099 /* Try connecting to the SIP hostname directly */
2100 SIPE_LOG_INFO_NOFORMAT("no SRV or A records found; using SIP domain as fallback");
2101 if (type == SIPE_TRANSPORT_AUTO)
2102 type = SIPE_TRANSPORT_TLS;
2104 sipe_server_register(sipe_private, type,
2105 g_strdup(sipe_private->public.sip_domain),
2107 return;
2111 /* Try to resolve next address */
2112 hostname = g_strdup_printf("%s.%s",
2113 sipe_private->address_data->prefix,
2114 sipe_private->public.sip_domain);
2115 sipe_private->dns_query = sipe_backend_dns_query_a(
2116 SIPE_CORE_PUBLIC,
2117 hostname,
2118 sipe_private->address_data->port,
2119 (sipe_dns_resolved_cb) sipe_core_dns_resolved,
2120 SIPE_CORE_PUBLIC);
2121 g_free(hostname);
2124 static void lync_autodiscover_cb(struct sipe_core_private *sipe_private,
2125 GSList *servers,
2126 SIPE_UNUSED_PARAMETER gpointer callback_data)
2128 if (servers) {
2129 /* Lync Autodiscover succeeded */
2130 SIPE_DEBUG_INFO_NOFORMAT("lync_autodiscover_cb: got server list");
2132 sipe_private->lync_autodiscover_servers = servers;
2133 resolve_next_lync(sipe_private);
2138 * NOTE: this function can be called before sipe_core_allocate()!
2140 gboolean sipe_core_transport_sip_requires_password(guint authentication,
2141 gboolean sso)
2143 return(sip_sec_requires_password(authentication, sso));
2146 void sipe_core_transport_sip_connect(struct sipe_core_public *sipe_public,
2147 guint transport,
2148 guint authentication,
2149 const gchar *server,
2150 const gchar *port)
2152 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
2154 /* backend initialization is complete */
2155 sipe_core_backend_initialized(sipe_private, authentication);
2158 * Initializing the certificate sub-system will trigger the generation
2159 * of a cryptographic key pair which takes time. If we do this after we
2160 * have connected to the server then there is a risk that we run into a
2161 * SIP connection timeout. So let's get this out of the way now...
2163 * This is currently only needed if the user has selected TLS-DSK.
2165 if (sipe_private->authentication_type == SIPE_AUTHENTICATION_TYPE_TLS_DSK)
2166 sipe_certificate_init(sipe_private);
2168 if (server) {
2169 /* Use user specified server[:port] */
2170 int port_number = 0;
2172 if (port)
2173 port_number = atoi(port);
2175 SIPE_LOG_INFO("sipe_core_connect: user specified SIP server %s:%d",
2176 server, port_number);
2178 sipe_server_register(sipe_private, transport,
2179 g_strdup(server), port_number);
2180 } else {
2181 /* Server auto-discovery */
2183 /* Remember user specified transport type */
2184 sipe_private->transport_type = transport;
2186 /* Start with Lync Autodiscover first */
2187 sipe_lync_autodiscover_start(sipe_private,
2188 lync_autodiscover_cb,
2189 NULL);
2193 const gchar *sipe_core_transport_sip_server_name(struct sipe_core_public *sipe_public)
2195 struct sip_transport *transport = SIPE_CORE_PRIVATE->transport;
2196 return(transport ? transport->server_name : NULL);
2199 int sip_transaction_cseq(struct transaction *trans)
2201 int cseq;
2203 g_return_val_if_fail(trans && trans->key, 0);
2205 sscanf(trans->key, "<%*[a-zA-Z0-9]><%d INVITE>", &cseq);
2206 return cseq;
2209 const gchar *sip_transport_epid(struct sipe_core_private *sipe_private)
2211 return(sipe_private->transport ?
2212 sipe_private->transport->epid :
2213 "0123456789ab");
2216 const gchar *sip_transport_ip_address(struct sipe_core_private *sipe_private)
2218 return(sipe_private->transport ?
2219 sipe_private->transport->ip_address :
2220 "0.0.0.0");
2224 Local Variables:
2225 mode: c
2226 c-file-style: "bsd"
2227 indent-tabs-mode: t
2228 tab-width: 8
2229 End: