transport: only check register retries for valid contexts
[siplcs.git] / src / core / sip-transport.c
blob5113ff74b15fe24019307c7a905f76f9b632b991
1 /**
2 * @file sip-transport.c
4 * pidgin-sipe
6 * Copyright (C) 2010-11 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.
51 #ifdef HAVE_CONFIG_H
52 #include "config.h"
53 #endif
55 #include <stdlib.h>
56 #include <string.h>
57 #include <stdio.h>
59 #include <glib.h>
61 #include "sipe-common.h"
62 #include "sipmsg.h"
63 #include "sip-sec.h"
64 #include "sip-transport.h"
65 #include "sipe-backend.h"
66 #include "sipe-core.h"
67 #include "sipe-core-private.h"
68 #include "sipe-certificate.h"
69 #include "sipe-dialog.h"
70 #include "sipe-incoming.h"
71 #include "sipe-nls.h"
72 #include "sipe-schedule.h"
73 #include "sipe-sign.h"
74 #include "sipe-subscriptions.h"
75 #include "sipe-utils.h"
76 #include "uuid.h"
77 #include "sipe.h"
79 struct sip_auth {
80 guint type;
81 struct sip_sec_context *gssapi_context;
82 gchar *gssapi_data;
83 gchar *opaque;
84 gchar *realm;
85 gchar *sts_uri;
86 gchar *target;
87 int version;
88 int retries;
89 int ntlm_num;
90 int expires;
93 /* sip-transport.c private data */
94 struct sip_transport {
95 struct sipe_transport_connection *connection;
97 gchar *server_name;
98 guint server_port;
99 gchar *server_version;
101 gchar *user_agent;
103 GSList *transactions;
105 struct sip_auth registrar;
106 struct sip_auth proxy;
108 guint cseq;
109 guint register_attempt;
111 gboolean processing_input; /* whether full header received */
112 gboolean auth_incomplete; /* whether authentication not completed */
113 gboolean reregister_set; /* whether reregister timer set */
114 gboolean reauthenticate_set; /* whether reauthenticate timer set */
115 gboolean subscribed; /* whether subscribed to events, except buddies presence */
118 /* Keep in sync with sipe_transport_type! */
119 static const char *transport_descriptor[] = { "", "tls", "tcp"};
120 #define TRANSPORT_DESCRIPTOR (transport_descriptor[transport->connection->type])
122 static char *genbranch()
124 return g_strdup_printf("z9hG4bK%04X%04X%04X%04X%04X",
125 rand() & 0xFFFF, rand() & 0xFFFF, rand() & 0xFFFF,
126 rand() & 0xFFFF, rand() & 0xFFFF);
129 static void sipe_auth_free(struct sip_auth *auth)
131 g_free(auth->opaque);
132 auth->opaque = NULL;
133 g_free(auth->realm);
134 auth->realm = NULL;
135 g_free(auth->sts_uri);
136 auth->sts_uri = NULL;
137 g_free(auth->target);
138 auth->target = NULL;
139 auth->version = 0;
140 auth->type = AUTH_TYPE_UNSET;
141 auth->retries = 0;
142 auth->expires = 0;
143 g_free(auth->gssapi_data);
144 auth->gssapi_data = NULL;
145 sip_sec_destroy_context(auth->gssapi_context);
146 auth->gssapi_context = NULL;
149 static void sipe_make_signature(struct sipe_core_private *sipe_private,
150 struct sipmsg *msg)
152 struct sip_transport *transport = sipe_private->transport;
153 if (transport->registrar.gssapi_context &&
154 sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
155 struct sipmsg_breakdown msgbd;
156 gchar *signature_input_str;
157 msgbd.msg = msg;
158 sipmsg_breakdown_parse(&msgbd, transport->registrar.realm, transport->registrar.target);
159 msgbd.rand = g_strdup_printf("%08x", g_random_int());
160 transport->registrar.ntlm_num++;
161 msgbd.num = g_strdup_printf("%d", transport->registrar.ntlm_num);
162 signature_input_str = sipmsg_breakdown_get_string(transport->registrar.version, &msgbd);
163 if (signature_input_str != NULL) {
164 char *signature_hex = sip_sec_make_signature(transport->registrar.gssapi_context, signature_input_str);
165 msg->signature = signature_hex;
166 msg->rand = g_strdup(msgbd.rand);
167 msg->num = g_strdup(msgbd.num);
168 g_free(signature_input_str);
170 sipmsg_breakdown_free(&msgbd);
174 static gchar *auth_header_version(struct sip_auth *auth)
176 return(auth->version > 2 ?
177 g_strdup_printf(", version=%d", auth->version) :
178 g_strdup(""));
181 static const gchar *const auth_type_to_protocol[] = {
182 NULL, /* AUTH_TYPE_UNSET */
183 "NTLM", /* AUTH_TYPE_NTLM */
184 "Kerberos", /* AUTH_TYPE_KERBEROS */
185 NULL, /* AUTH_TYPE_NEGOTIATE */
186 "TLS-DSK", /* AUTH_TYPE_TLS_DSK */
188 #define AUTH_PROTOCOLS (sizeof(auth_type_to_protocol)/sizeof(gchar *))
190 static gchar *msg_signature_to_auth(struct sip_auth *auth,
191 struct sipmsg *msg)
193 return(g_strdup_printf("%s qop=\"auth\", opaque=\"%s\", realm=\"%s\", targetname=\"%s\", crand=\"%s\", cnum=\"%s\", response=\"%s\"",
194 auth_type_to_protocol[auth->type],
195 auth->opaque, auth->realm, auth->target,
196 msg->rand, msg->num, msg->signature));
199 static gchar *initialize_auth_context(struct sipe_core_private *sipe_private,
200 struct sip_auth *auth,
201 struct sipmsg *msg)
203 gchar *ret;
204 gchar *gssapi_data = NULL;
205 gchar *sign_str;
206 gchar *gssapi_str;
207 gchar *opaque_str;
208 gchar *version_str;
210 /* Create security context or handshake continuation? */
211 if (auth->gssapi_context) {
212 /* Perform next step in authentication handshake */
213 int status = sip_sec_init_context_step(auth->gssapi_context,
214 auth->target,
215 auth->gssapi_data,
216 &gssapi_data,
217 &auth->expires);
219 /* If authentication is completed gssapi_data can be NULL */
220 if ((status < 0) ||
221 !(sip_sec_context_is_ready(auth->gssapi_context) || gssapi_data)) {
222 SIPE_DEBUG_ERROR_NOFORMAT("initialize_auth_context: security context continuation failed");
223 g_free(gssapi_data);
224 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
225 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
226 _("Failed to authenticate to server"));
227 return NULL;
230 } else {
231 /* Create security context */
232 struct sipe_account_data *sip = SIPE_ACCOUNT_DATA_PRIVATE;
233 const gchar *authuser = sip->authuser;
234 gpointer password = sip->password;
236 if (is_empty(authuser)) {
237 authuser = sipe_private->username;
240 /* For TLS-DSK the "password" is a certificate */
241 if (auth->type == AUTH_TYPE_TLS_DSK) {
242 password = sipe_certificate_tls_dsk_find(sipe_private,
243 auth->target);
245 if (!password) {
246 if (auth->sts_uri) {
247 SIPE_DEBUG_INFO("initialize_auth_context: TLS-DSK Certificate Provisioning URI %s",
248 auth->sts_uri);
249 if (!sipe_certificate_tls_dsk_generate(sipe_private,
250 auth->target,
251 authuser,
252 auth->sts_uri)) {
253 gchar *tmp = g_strdup_printf(_("Can't request certificate from %s"),
254 auth->sts_uri);
255 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
256 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
257 tmp);
258 g_free(tmp);
260 } else {
261 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
262 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
263 _("No URI for certificate provisioning service provided"));
266 /* we can't authenticate the message yet */
267 sipe_private->transport->auth_incomplete = TRUE;
268 return(NULL);
269 } else {
270 SIPE_DEBUG_INFO("initialize_auth_context: TLS-DSK certificate for target '%s' found.",
271 auth->target);
275 gssapi_data = sip_sec_init_context(&(auth->gssapi_context),
276 &(auth->expires),
277 auth->type,
278 SIPE_CORE_PUBLIC_FLAG_IS(SSO),
279 sip->authdomain ? sip->authdomain : "",
280 authuser,
281 password,
282 auth->target,
283 auth->gssapi_data);
284 if (!gssapi_data || !auth->gssapi_context) {
285 g_free(gssapi_data);
286 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
287 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
288 _("Failed to authenticate to server"));
289 return NULL;
293 if ((auth->version > 3) &&
294 sip_sec_context_is_ready(auth->gssapi_context)) {
295 sipe_make_signature(sipe_private, msg);
296 sign_str = g_strdup_printf(", crand=\"%s\", cnum=\"%s\", response=\"%s\"",
297 msg->rand, msg->num, msg->signature);
298 } else {
299 sign_str = g_strdup("");
302 if (gssapi_data) {
303 gssapi_str = g_strdup_printf(", gssapi-data=\"%s\"",
304 gssapi_data);
305 g_free(gssapi_data);
306 } else {
307 gssapi_str = g_strdup("");
310 opaque_str = auth->opaque ? g_strdup_printf(", opaque=\"%s\"", auth->opaque) : g_strdup("");
311 version_str = auth_header_version(auth);
312 ret = g_strdup_printf("%s qop=\"auth\"%s, realm=\"%s\", targetname=\"%s\"%s%s%s",
313 auth_type_to_protocol[auth->type], opaque_str,
314 auth->realm, auth->target,
315 gssapi_str, version_str, sign_str);
316 g_free(version_str);
317 g_free(opaque_str);
318 g_free(gssapi_str);
319 g_free(sign_str);
321 return(ret);
324 static gchar *start_auth_handshake(struct sip_auth *auth)
326 gchar *version_str = auth_header_version(auth);
327 gchar *ret = g_strdup_printf("%s qop=\"auth\", realm=\"%s\", targetname=\"%s\", gssapi-data=\"\"%s",
328 auth_type_to_protocol[auth->type],
329 auth->realm, auth->target,
330 version_str);
331 g_free(version_str);
332 return(ret);
335 static gchar *auth_header(struct sipe_core_private *sipe_private,
336 struct sip_auth *auth,
337 struct sipmsg *msg)
339 gchar *ret = NULL;
342 * If the message is already signed then we have an authentication
343 * context, i.e. the authentication handshake is complete. Generate
344 * authentication header from message signature.
346 if (msg->signature) {
347 ret = msg_signature_to_auth(auth, msg);
350 * If the message isn't signed then we don't have a initialized
351 * authentication context yet.
353 * Start the authentication handshake if NTLM is selected.
355 } else if ((auth->type == AUTH_TYPE_NTLM) && !auth->gssapi_data) {
356 ret = start_auth_handshake(auth);
359 * We should reach this point only when the authentication context
360 * needs to be initialized.
362 } else {
363 ret = initialize_auth_context(sipe_private, auth, msg);
366 return(ret);
369 static void fill_auth(const gchar *hdr, struct sip_auth *auth)
371 const gchar *param;
373 /* skip authentication identifier */
374 hdr = strchr(hdr, ' ');
375 if (!hdr) {
376 SIPE_DEBUG_ERROR_NOFORMAT("fill_auth: corrupted authentication header");
377 return;
379 while (*hdr == ' ')
380 hdr++;
382 /* start of next parameter value */
383 while ((param = strchr(hdr, '=')) != NULL) {
384 const gchar *end;
386 /* parameter value type */
387 param++;
388 if (*param == '"') {
389 /* string: xyz="..."(,) */
390 end = strchr(++param, '"');
391 if (!end) {
392 SIPE_DEBUG_ERROR("fill_auth: corrupted string parameter near '%s'", hdr);
393 break;
395 } else {
396 /* number: xyz=12345(,) */
397 end = strchr(param, ',');
398 if (!end) {
399 /* last parameter */
400 end = param + strlen(param);
404 #if 0
405 SIPE_DEBUG_INFO("fill_auth: hdr '%s'", hdr);
406 SIPE_DEBUG_INFO("fill_auth: param '%s'", param);
407 SIPE_DEBUG_INFO("fill_auth: end '%s'", end);
408 #endif
410 /* parameter type */
411 if (g_str_has_prefix(hdr, "gssapi-data=\"")) {
412 g_free(auth->gssapi_data);
413 auth->gssapi_data = g_strndup(param, end - param);
414 } else if (g_str_has_prefix(hdr, "opaque=\"")) {
415 g_free(auth->opaque);
416 auth->opaque = g_strndup(param, end - param);
417 } else if (g_str_has_prefix(hdr, "realm=\"")) {
418 g_free(auth->realm);
419 auth->realm = g_strndup(param, end - param);
420 } else if (g_str_has_prefix(hdr, "sts-uri=\"")) {
421 /* Only used with AUTH_TYPE_TLS_DSK */
422 g_free(auth->sts_uri);
423 auth->sts_uri = g_strndup(param, end - param);
424 } else if (g_str_has_prefix(hdr, "targetname=\"")) {
425 g_free(auth->target);
426 auth->target = g_strndup(param, end - param);
427 } else if (g_str_has_prefix(hdr, "version=")) {
428 auth->version = atoi(param);
431 /* skip to next parameter */
432 while ((*end == '"') || (*end == ',') || (*end == ' '))
433 end++;
434 hdr = end;
437 return;
440 static void sign_outgoing_message(struct sipe_core_private *sipe_private,
441 struct sipmsg *msg)
443 struct sip_transport *transport = sipe_private->transport;
444 gchar *buf;
446 if (transport->registrar.type == AUTH_TYPE_UNSET) {
447 return;
450 sipe_make_signature(sipe_private, msg);
452 buf = auth_header(sipe_private, &transport->registrar, msg);
453 if (buf) {
454 sipmsg_add_header_now_pos(msg, "Authorization", buf, 5);
455 g_free(buf);
459 static const gchar *sip_transport_user_agent(struct sipe_core_private *sipe_private)
461 struct sip_transport *transport = sipe_private->transport;
463 if (!transport->user_agent) {
464 const gchar *useragent = sipe_backend_setting(SIPE_CORE_PUBLIC,
465 SIPE_SETTING_USER_AGENT);
466 if (is_empty(useragent)) {
467 /*@TODO: better approach to define _user_ OS, it's version and host architecture */
468 /* ref: lzodefs.h */
469 #if defined(__linux__) || defined(__linux) || defined(__LINUX__)
470 #define SIPE_TARGET_PLATFORM "linux"
471 #elif defined(__NetBSD__) ||defined( __OpenBSD__) || defined(__FreeBSD__)
472 #define SIPE_TARGET_PLATFORM "bsd"
473 #elif defined(__APPLE__) || defined(__MACOS__)
474 #define SIPE_TARGET_PLATFORM "macosx"
475 #elif defined(_AIX) || defined(__AIX__) || defined(__aix__)
476 #define SIPE_TARGET_PLATFORM "aix"
477 #elif defined(__solaris__) || defined(__sun)
478 #define SIPE_TARGET_PLATFORM "sun"
479 #elif defined(_WIN32)
480 #define SIPE_TARGET_PLATFORM "win"
481 #elif defined(__CYGWIN__)
482 #define SIPE_TARGET_PLATFORM "cygwin"
483 #elif defined(__hpux__)
484 #define SIPE_TARGET_PLATFORM "hpux"
485 #elif defined(__sgi__)
486 #define SIPE_TARGET_PLATFORM "irix"
487 #else
488 #define SIPE_TARGET_PLATFORM "unknown"
489 #endif
491 #if defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)
492 #define SIPE_TARGET_ARCH "x86_64"
493 #elif defined(__386__) || defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_M_I386)
494 #define SIPE_TARGET_ARCH "i386"
495 #elif defined(__ppc64__)
496 #define SIPE_TARGET_ARCH "ppc64"
497 #elif defined(__powerpc__) || defined(__powerpc) || defined(__ppc__) || defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PWR)
498 #define SIPE_TARGET_ARCH "ppc"
499 #elif defined(__hppa__) || defined(__hppa)
500 #define SIPE_TARGET_ARCH "hppa"
501 #elif defined(__mips__) || defined(__mips) || defined(_MIPS_ARCH) || defined(_M_MRX000)
502 #define SIPE_TARGET_ARCH "mips"
503 #elif defined(__s390__) || defined(__s390) || defined(__s390x__) || defined(__s390x)
504 #define SIPE_TARGET_ARCH "s390"
505 #elif defined(__sparc__) || defined(__sparc) || defined(__sparcv8)
506 #define SIPE_TARGET_ARCH "sparc"
507 #elif defined(__arm__)
508 #define SIPE_TARGET_ARCH "arm"
509 #else
510 #define SIPE_TARGET_ARCH "other"
511 #endif
512 gchar *backend = sipe_backend_version();
513 transport->user_agent = g_strdup_printf("%s Sipe/" PACKAGE_VERSION " (" SIPE_TARGET_PLATFORM "-" SIPE_TARGET_ARCH "; %s)",
514 backend,
515 transport->server_version ? transport->server_version : "");
516 g_free(backend);
517 } else {
518 transport->user_agent = g_strdup(useragent);
521 return(transport->user_agent);
524 void sip_transport_response(struct sipe_core_private *sipe_private,
525 struct sipmsg *msg,
526 guint code,
527 const char *text,
528 const char *body)
530 gchar *name;
531 gchar *value;
532 GString *outstr = g_string_new("");
533 gchar *contact;
534 GSList *tmp;
535 const gchar *keepers[] = { "To", "From", "Call-ID", "CSeq", "Via", "Record-Route", NULL };
537 /* Can return NULL! */
538 contact = get_contact(sipe_private);
539 if (contact) {
540 sipmsg_add_header(msg, "Contact", contact);
541 g_free(contact);
544 if (body) {
545 gchar *len = g_strdup_printf("%" G_GSIZE_FORMAT , (gsize) strlen(body));
546 sipmsg_add_header(msg, "Content-Length", len);
547 g_free(len);
548 } else {
549 sipmsg_add_header(msg, "Content-Length", "0");
552 sipmsg_add_header(msg, "User-Agent", sip_transport_user_agent(sipe_private));
554 msg->response = code;
556 sipmsg_strip_headers(msg, keepers);
557 sipmsg_merge_new_headers(msg);
558 sign_outgoing_message(sipe_private, msg);
560 g_string_append_printf(outstr, "SIP/2.0 %d %s\r\n", code, text);
561 tmp = msg->headers;
562 while (tmp) {
563 name = ((struct sipnameval*) (tmp->data))->name;
564 value = ((struct sipnameval*) (tmp->data))->value;
566 g_string_append_printf(outstr, "%s: %s\r\n", name, value);
567 tmp = g_slist_next(tmp);
569 g_string_append_printf(outstr, "\r\n%s", body ? body : "");
570 sipe_utils_message_debug("SIP", outstr->str, NULL, TRUE);
571 sipe_backend_transport_message(sipe_private->transport->connection, outstr->str);
572 g_string_free(outstr, TRUE);
575 static void transactions_remove(struct sipe_core_private *sipe_private,
576 struct transaction *trans)
578 struct sip_transport *transport = sipe_private->transport;
579 if (transport->transactions) {
580 transport->transactions = g_slist_remove(transport->transactions,
581 trans);
582 SIPE_DEBUG_INFO("SIP transactions count:%d after removal", g_slist_length(transport->transactions));
584 if (trans->msg) sipmsg_free(trans->msg);
585 if (trans->payload) {
586 (*trans->payload->destroy)(trans->payload->data);
587 g_free(trans->payload);
589 g_free(trans->key);
590 if (trans->timeout_key) {
591 sipe_schedule_cancel(sipe_private, trans->timeout_key);
592 g_free(trans->timeout_key);
594 g_free(trans);
598 static struct transaction *transactions_find(struct sip_transport *transport,
599 struct sipmsg *msg)
601 GSList *transactions = transport->transactions;
602 const gchar *call_id = sipmsg_find_header(msg, "Call-ID");
603 const gchar *cseq = sipmsg_find_header(msg, "CSeq");
604 gchar *key;
606 if (!call_id || !cseq) {
607 SIPE_DEBUG_ERROR_NOFORMAT("transaction_find: no Call-ID or CSeq!");
608 return NULL;
611 key = g_strdup_printf("<%s><%s>", call_id, cseq);
612 while (transactions) {
613 struct transaction *trans = transactions->data;
614 if (!g_strcasecmp(trans->key, key)) {
615 g_free(key);
616 return trans;
618 transactions = transactions->next;
620 g_free(key);
622 return NULL;
625 static void transaction_timeout_cb(struct sipe_core_private *sipe_private,
626 gpointer data)
628 struct transaction *trans = data;
629 (trans->timeout_callback)(sipe_private, trans->msg, trans);
630 transactions_remove(sipe_private, trans);
633 struct transaction *sip_transport_request_timeout(struct sipe_core_private *sipe_private,
634 const gchar *method,
635 const gchar *url,
636 const gchar *to,
637 const gchar *addheaders,
638 const gchar *body,
639 struct sip_dialog *dialog,
640 TransCallback callback,
641 guint timeout,
642 TransCallback timeout_callback)
644 struct sip_transport *transport = sipe_private->transport;
645 struct sipe_account_data *sip = SIPE_ACCOUNT_DATA_PRIVATE;
646 char *buf;
647 struct sipmsg *msg;
648 gchar *ourtag = dialog && dialog->ourtag ? g_strdup(dialog->ourtag) : NULL;
649 gchar *theirtag = dialog && dialog->theirtag ? g_strdup(dialog->theirtag) : NULL;
650 gchar *theirepid = dialog && dialog->theirepid ? g_strdup(dialog->theirepid) : NULL;
651 gchar *callid = dialog && dialog->callid ? g_strdup(dialog->callid) : gencallid();
652 gchar *branch = dialog && dialog->callid ? NULL : genbranch();
653 gchar *route = g_strdup("");
654 gchar *epid = get_epid(sipe_private);
655 int cseq = dialog ? ++dialog->cseq : 1 /* as Call-Id is new in this case */;
656 struct transaction *trans = NULL;
658 if (dialog && dialog->routes)
660 GSList *iter = dialog->routes;
662 while(iter)
664 char *tmp = route;
665 route = g_strdup_printf("%sRoute: %s\r\n", route, (char *)iter->data);
666 g_free(tmp);
667 iter = g_slist_next(iter);
671 if (!ourtag && !dialog) {
672 ourtag = gentag();
675 if (sipe_strequal(method, "REGISTER")) {
676 if (sip->regcallid) {
677 g_free(callid);
678 callid = g_strdup(sip->regcallid);
679 } else {
680 sip->regcallid = g_strdup(callid);
682 cseq = ++transport->cseq;
685 buf = g_strdup_printf("%s %s SIP/2.0\r\n"
686 "Via: SIP/2.0/%s %s:%d%s%s\r\n"
687 "From: <sip:%s>%s%s;epid=%s\r\n"
688 "To: <%s>%s%s%s%s\r\n"
689 "Max-Forwards: 70\r\n"
690 "CSeq: %d %s\r\n"
691 "User-Agent: %s\r\n"
692 "Call-ID: %s\r\n"
693 "%s%s"
694 "Content-Length: %" G_GSIZE_FORMAT "\r\n\r\n%s",
695 method,
696 dialog && dialog->request ? dialog->request : url,
697 TRANSPORT_DESCRIPTOR,
698 sipe_backend_network_ip_address(),
699 transport->connection->client_port,
700 branch ? ";branch=" : "",
701 branch ? branch : "",
702 sipe_private->username,
703 ourtag ? ";tag=" : "",
704 ourtag ? ourtag : "",
705 epid,
707 theirtag ? ";tag=" : "",
708 theirtag ? theirtag : "",
709 theirepid ? ";epid=" : "",
710 theirepid ? theirepid : "",
711 cseq,
712 method,
713 sip_transport_user_agent(sipe_private),
714 callid,
715 route,
716 addheaders ? addheaders : "",
717 body ? (gsize) strlen(body) : 0,
718 body ? body : "");
721 //printf ("parsing msg buf:\n%s\n\n", buf);
722 msg = sipmsg_parse_msg(buf);
724 g_free(buf);
725 g_free(ourtag);
726 g_free(theirtag);
727 g_free(theirepid);
728 g_free(branch);
729 g_free(route);
730 g_free(epid);
732 sign_outgoing_message(sipe_private, msg);
734 /* The authentication scheme is not ready so we can't send the message.
735 This should only happen for REGISTER messages. */
736 if (!transport->auth_incomplete) {
737 buf = sipmsg_to_string(msg);
739 /* add to ongoing transactions */
740 /* ACK isn't supposed to be answered ever. So we do not keep transaction for it. */
741 if (!sipe_strequal(method, "ACK")) {
742 trans = g_new0(struct transaction, 1);
743 trans->callback = callback;
744 trans->msg = msg;
745 trans->key = g_strdup_printf("<%s><%d %s>", callid, cseq, method);
746 if (timeout_callback) {
747 trans->timeout_callback = timeout_callback;
748 trans->timeout_key = g_strdup_printf("<transaction timeout>%s", trans->key);
749 sipe_schedule_seconds(sipe_private,
750 trans->timeout_key,
751 trans,
752 timeout,
753 transaction_timeout_cb,
754 NULL);
756 transport->transactions = g_slist_append(transport->transactions,
757 trans);
758 SIPE_DEBUG_INFO("SIP transactions count:%d after addition", g_slist_length(transport->transactions));
761 sipe_utils_message_debug("SIP", buf, NULL, TRUE);
762 sipe_backend_transport_message(transport->connection, buf);
763 g_free(buf);
766 if (!trans) sipmsg_free(msg);
767 g_free(callid);
768 return trans;
771 struct transaction *sip_transport_request(struct sipe_core_private *sipe_private,
772 const gchar *method,
773 const gchar *url,
774 const gchar *to,
775 const gchar *addheaders,
776 const gchar *body,
777 struct sip_dialog *dialog,
778 TransCallback callback)
780 return sip_transport_request_timeout(sipe_private,
781 method,
782 url,
784 addheaders,
785 body,
786 dialog,
787 callback,
789 NULL);
792 static void sip_transport_simple_request(struct sipe_core_private *sipe_private,
793 const gchar *method,
794 struct sip_dialog *dialog)
796 sip_transport_request(sipe_private,
797 method,
798 dialog->with,
799 dialog->with,
800 NULL,
801 NULL,
802 dialog,
803 NULL);
806 void sip_transport_ack(struct sipe_core_private *sipe_private,
807 struct sip_dialog *dialog)
809 sip_transport_simple_request(sipe_private, "ACK", dialog);
812 void sip_transport_bye(struct sipe_core_private *sipe_private,
813 struct sip_dialog *dialog)
815 sip_transport_simple_request(sipe_private, "BYE", dialog);
818 struct transaction *sip_transport_info(struct sipe_core_private *sipe_private,
819 const gchar *addheaders,
820 const gchar *body,
821 struct sip_dialog *dialog,
822 TransCallback callback)
824 return sip_transport_request(sipe_private,
825 "INFO",
826 dialog->with,
827 dialog->with,
828 addheaders,
829 body,
830 dialog,
831 callback);
834 struct transaction *sip_transport_invite(struct sipe_core_private *sipe_private,
835 const gchar *addheaders,
836 const gchar *body,
837 struct sip_dialog *dialog,
838 TransCallback callback)
840 return sip_transport_request(sipe_private,
841 "INVITE",
842 dialog->with,
843 dialog->with,
844 addheaders,
845 body,
846 dialog,
847 callback);
850 struct transaction *sip_transport_service(struct sipe_core_private *sipe_private,
851 const gchar *uri,
852 const gchar *addheaders,
853 const gchar *body,
854 TransCallback callback)
856 return sip_transport_request(sipe_private,
857 "SERVICE",
858 uri,
859 uri,
860 addheaders,
861 body,
862 NULL,
863 callback);
866 void sip_transport_subscribe(struct sipe_core_private *sipe_private,
867 const gchar *uri,
868 const gchar *addheaders,
869 const gchar *body,
870 struct sip_dialog *dialog,
871 TransCallback callback)
873 sip_transport_request(sipe_private,
874 "SUBSCRIBE",
875 uri,
876 uri,
877 addheaders,
878 body,
879 dialog,
880 callback);
883 static const gchar *get_auth_header(struct sipe_core_private *sipe_private,
884 struct sip_auth *auth,
885 struct sipmsg *msg)
887 auth->type = AUTH_TYPE_NTLM;
888 #if defined(HAVE_LIBKRB5) || defined(HAVE_SSPI)
889 if (SIPE_CORE_PUBLIC_FLAG_IS(KRB5)) {
890 auth->type = AUTH_TYPE_KERBEROS;
892 #endif
893 if (SIPE_CORE_PUBLIC_FLAG_IS(TLS_DSK)) {
894 auth->type = AUTH_TYPE_TLS_DSK;
896 return(sipmsg_find_auth_header(msg,
897 auth_type_to_protocol[auth->type]));
900 static void do_register(struct sipe_core_private *sipe_private,
901 gboolean deregister);
903 static void do_reauthenticate_cb(struct sipe_core_private *sipe_private,
904 SIPE_UNUSED_PARAMETER gpointer unused)
906 struct sip_transport *transport = sipe_private->transport;
908 /* register again when security token expires */
909 /* we have to start a new authentication as the security token
910 * is almost expired by sending a not signed REGISTER message */
911 SIPE_DEBUG_INFO_NOFORMAT("do a full reauthentication");
912 sipe_auth_free(&transport->registrar);
913 sipe_auth_free(&transport->proxy);
914 sipe_schedule_cancel(sipe_private, "<registration>");
915 transport->reregister_set = FALSE;
916 transport->register_attempt = 0;
917 do_register(sipe_private, FALSE);
918 transport->reauthenticate_set = FALSE;
921 static void sip_transport_default_contact(struct sipe_core_private *sipe_private)
923 struct sip_transport *transport = sipe_private->transport;
924 sipe_private->contact = g_strdup_printf("<sip:%s:%d;maddr=%s;transport=%s>;proxy=replace",
925 sipe_private->username,
926 transport->connection->client_port,
927 sipe_backend_network_ip_address(),
928 TRANSPORT_DESCRIPTOR);
931 static void do_register_cb(struct sipe_core_private *sipe_private,
932 SIPE_UNUSED_PARAMETER void *unused)
934 do_register(sipe_private, FALSE);
937 static void sip_transport_set_reregister(struct sipe_core_private *sipe_private,
938 int expires)
940 sipe_schedule_seconds(sipe_private,
941 "<registration>",
942 NULL,
943 expires,
944 do_register_cb,
945 NULL);
948 static void sipe_server_register(struct sipe_core_private *sipe_private,
949 guint type,
950 gchar *server_name,
951 guint server_port);
953 static gboolean process_register_response(struct sipe_core_private *sipe_private,
954 struct sipmsg *msg,
955 SIPE_UNUSED_PARAMETER struct transaction *trans)
957 struct sip_transport *transport = sipe_private->transport;
958 struct sipe_account_data *sip = SIPE_ACCOUNT_DATA_PRIVATE;
959 const gchar *expires_header;
960 int expires, i;
961 GSList *hdr = msg->headers;
962 struct sipnameval *elem;
964 expires_header = sipmsg_find_header(msg, "Expires");
965 expires = expires_header != NULL ? strtol(expires_header, NULL, 10) : 0;
966 SIPE_DEBUG_INFO("process_register_response: got response to REGISTER; expires = %d", expires);
968 switch (msg->response) {
969 case 200:
970 if (expires) {
971 const gchar *contact_hdr;
972 const gchar *auth_hdr;
973 gchar *gruu = NULL;
974 gchar *uuid;
975 gchar *timeout;
976 const gchar *server_hdr = sipmsg_find_header(msg, "Server");
978 if (!transport->reregister_set) {
979 sip_transport_set_reregister(sipe_private,
980 expires);
981 transport->reregister_set = TRUE;
984 if (server_hdr && !transport->server_version) {
985 transport->server_version = g_strdup(server_hdr);
986 g_free(transport->user_agent);
987 transport->user_agent = NULL;
990 auth_hdr = get_auth_header(sipe_private, &transport->registrar, msg);
991 if (auth_hdr) {
992 SIPE_DEBUG_INFO("process_register_response: Auth header: %s", auth_hdr);
993 fill_auth(auth_hdr, &transport->registrar);
996 if (!transport->reauthenticate_set) {
997 gchar *action_name = g_strdup_printf("<%s>", "+reauthentication");
998 guint reauth_timeout;
999 if (transport->registrar.type == AUTH_TYPE_KERBEROS && transport->registrar.expires > 0) {
1000 /* assuming normal Kerberos ticket expiration of about 8-10 hours */
1001 reauth_timeout = transport->registrar.expires - 300;
1002 } else {
1003 /* NTLM: we have to reauthenticate as our security token expires
1004 after eight hours (be five minutes early) */
1005 reauth_timeout = (8 * 3600) - 300;
1007 sipe_schedule_seconds(sipe_private,
1008 action_name,
1009 NULL,
1010 reauth_timeout,
1011 do_reauthenticate_cb,
1012 NULL);
1013 g_free(action_name);
1014 transport->reauthenticate_set = TRUE;
1017 sipe_backend_connection_completed(SIPE_CORE_PUBLIC);
1019 uuid = get_uuid(sipe_private);
1021 // There can be multiple Contact headers (one per location where the user is logged in) so
1022 // make sure to only get the one for this uuid
1023 for (i = 0; (contact_hdr = sipmsg_find_header_instance (msg, "Contact", i)); i++) {
1024 gchar * valid_contact = sipmsg_find_part_of_header (contact_hdr, uuid, NULL, NULL);
1025 if (valid_contact) {
1026 gruu = sipmsg_find_part_of_header(contact_hdr, "gruu=\"", "\"", NULL);
1027 //SIPE_DEBUG_INFO("process_register_response: got gruu %s from contact hdr w/ right uuid: %s", gruu, contact_hdr);
1028 g_free(valid_contact);
1029 break;
1030 } else {
1031 //SIPE_DEBUG_INFO("process_register_response: ignoring contact hdr b/c not right uuid: %s", contact_hdr);
1034 g_free(uuid);
1036 g_free(sipe_private->contact);
1037 if(gruu) {
1038 sipe_private->contact = g_strdup_printf("<%s>", gruu);
1039 g_free(gruu);
1040 } else {
1041 //SIPE_DEBUG_INFO_NOFORMAT("process_register_response: didn't find gruu in a Contact hdr");
1042 sip_transport_default_contact(sipe_private);
1044 SIPE_CORE_PRIVATE_FLAG_UNSET(OCS2007);
1045 SIPE_CORE_PRIVATE_FLAG_UNSET(REMOTE_USER);
1046 sip->batched_support = FALSE;
1048 while(hdr)
1050 elem = hdr->data;
1051 if (sipe_strcase_equal(elem->name, "Supported")) {
1052 if (sipe_strcase_equal(elem->value, "msrtc-event-categories")) {
1053 /* We interpret this as OCS2007+ indicator */
1054 SIPE_CORE_PRIVATE_FLAG_SET(OCS2007);
1055 SIPE_DEBUG_INFO("Supported: %s (indicates OCS2007+)", elem->value);
1057 if (sipe_strcase_equal(elem->value, "adhoclist")) {
1058 sip->batched_support = TRUE;
1059 SIPE_DEBUG_INFO("Supported: %s", elem->value);
1062 if (sipe_strcase_equal(elem->name, "Allow-Events")){
1063 gchar **caps = g_strsplit(elem->value,",",0);
1064 i = 0;
1065 while (caps[i]) {
1066 sip->allow_events = g_slist_append(sip->allow_events, g_strdup(caps[i]));
1067 SIPE_DEBUG_INFO("Allow-Events: %s", caps[i]);
1068 i++;
1070 g_strfreev(caps);
1072 if (sipe_strcase_equal(elem->name, "ms-user-logon-data")) {
1073 if (sipe_strcase_equal(elem->value, "RemoteUser")) {
1074 SIPE_CORE_PRIVATE_FLAG_SET(REMOTE_USER);
1075 SIPE_DEBUG_INFO_NOFORMAT("ms-user-logon-data: RemoteUser (connected "
1076 "via Edge Server)");
1079 hdr = g_slist_next(hdr);
1082 /* rejoin open chats to be able to use them by continue to send messages */
1083 sipe_backend_chat_rejoin_all(SIPE_CORE_PUBLIC);
1085 /* subscriptions */
1086 if (!transport->subscribed) { //do it just once, not every re-register
1088 if (g_slist_find_custom(sip->allow_events, "vnd-microsoft-roaming-contacts",
1089 (GCompareFunc)g_ascii_strcasecmp)) {
1090 sipe_subscribe_roaming_contacts(sipe_private);
1093 /* For 2007+ it does not make sence to subscribe to:
1094 * vnd-microsoft-roaming-ACL
1095 * vnd-microsoft-provisioning (not v2)
1096 * presence.wpending
1097 * These are for backward compatibility.
1099 if (SIPE_CORE_PRIVATE_FLAG_IS(OCS2007))
1101 if (g_slist_find_custom(sip->allow_events, "vnd-microsoft-roaming-self",
1102 (GCompareFunc)g_ascii_strcasecmp)) {
1103 sipe_subscribe_roaming_self(sipe_private);
1105 if (g_slist_find_custom(sip->allow_events, "vnd-microsoft-provisioning-v2",
1106 (GCompareFunc)g_ascii_strcasecmp)) {
1107 sipe_subscribe_roaming_provisioning_v2(sipe_private);
1110 /* For 2005- servers */
1111 else
1113 //sipe_options_request(sip, sipe_private->public.sip_domain);
1115 if (g_slist_find_custom(sip->allow_events, "vnd-microsoft-roaming-ACL",
1116 (GCompareFunc)g_ascii_strcasecmp)) {
1117 sipe_subscribe_roaming_acl(sipe_private);
1119 if (g_slist_find_custom(sip->allow_events, "vnd-microsoft-provisioning",
1120 (GCompareFunc)g_ascii_strcasecmp)) {
1121 sipe_subscribe_roaming_provisioning(sipe_private);
1123 if (g_slist_find_custom(sip->allow_events, "presence.wpending",
1124 (GCompareFunc)g_ascii_strcasecmp)) {
1125 sipe_subscribe_presence_wpending(sipe_private,
1126 NULL);
1129 /* For 2007+ we publish our initial statuses and calendar data only after
1130 * received our existing publications in sipe_process_roaming_self()
1131 * Only in this case we know versions of current publications made
1132 * on our behalf.
1134 /* For 2005- we publish our initial statuses only after
1135 * received our existing UserInfo data in response to
1136 * self subscription.
1137 * Only in this case we won't override existing UserInfo data
1138 * set earlier or by other client on our behalf.
1142 transport->subscribed = TRUE;
1145 timeout = sipmsg_find_part_of_header(sipmsg_find_header(msg, "ms-keep-alive"),
1146 "timeout=", ";", NULL);
1147 if (timeout != NULL) {
1148 sscanf(timeout, "%u", &sipe_private->public.keepalive_timeout);
1149 SIPE_DEBUG_INFO("process_register_response: server determined keep alive timeout is %u seconds",
1150 sipe_private->public.keepalive_timeout);
1151 g_free(timeout);
1154 SIPE_DEBUG_INFO("process_register_response: got 200, removing CSeq: %d", transport->cseq);
1156 break;
1157 case 301:
1159 gchar *redirect = parse_from(sipmsg_find_header(msg, "Contact"));
1161 if (redirect && (g_strncasecmp("sip:", redirect, 4) == 0)) {
1162 gchar **parts = g_strsplit(redirect + 4, ";", 0);
1163 gchar **tmp;
1164 gchar *hostname;
1165 int port = 0;
1166 guint transport = SIPE_TRANSPORT_TLS;
1167 int i = 1;
1169 tmp = g_strsplit(parts[0], ":", 0);
1170 hostname = g_strdup(tmp[0]);
1171 if (tmp[1]) port = strtoul(tmp[1], NULL, 10);
1172 g_strfreev(tmp);
1174 while (parts[i]) {
1175 tmp = g_strsplit(parts[i], "=", 0);
1176 if (tmp[1]) {
1177 if (g_strcasecmp("transport", tmp[0]) == 0) {
1178 if (g_strcasecmp("tcp", tmp[1]) == 0) {
1179 transport = SIPE_TRANSPORT_TCP;
1183 g_strfreev(tmp);
1184 i++;
1186 g_strfreev(parts);
1188 /* Close old connection */
1189 sipe_connection_cleanup(sipe_private);
1191 /* Create new connection */
1192 sipe_server_register(sipe_private, transport, hostname, port);
1193 SIPE_DEBUG_INFO("process_register_response: redirected to host %s port %d transport %d",
1194 hostname, port, transport);
1196 g_free(redirect);
1198 break;
1199 case 401:
1201 const char *auth_hdr;
1203 SIPE_DEBUG_INFO("process_register_response: REGISTER retries %d", transport->registrar.retries);
1204 if (transport->registrar.gssapi_context &&
1205 sip_sec_context_is_ready(transport->registrar.gssapi_context) &&
1206 (transport->registrar.retries > 2)) {
1207 SIPE_DEBUG_INFO("process_register_response: still not authenticated after %d tries - giving up.",
1208 transport->registrar.retries);
1209 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1210 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
1211 _("Authentication failed"));
1212 return TRUE;
1215 if (transport->reauthenticate_set) {
1216 SIPE_DEBUG_ERROR_NOFORMAT("process_register_response: RE-REGISTER rejected, triggering re-authentication");
1217 do_reauthenticate_cb(sipe_private, NULL);
1218 return TRUE;
1221 auth_hdr = get_auth_header(sipe_private, &transport->registrar, msg);
1222 if (!auth_hdr) {
1223 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1224 SIPE_CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE,
1225 _("Incompatible authentication scheme chosen"));
1226 return TRUE;
1228 SIPE_DEBUG_INFO("process_register_response: Auth header: %s", auth_hdr);
1229 fill_auth(auth_hdr, &transport->registrar);
1230 transport->reregister_set = FALSE;
1231 transport->register_attempt = 0;
1232 do_register(sipe_private,
1233 sipe_backend_connection_is_disconnecting(SIPE_CORE_PUBLIC));
1235 break;
1236 case 403:
1238 gchar *reason;
1239 gchar *warning;
1240 sipmsg_parse_warning(msg, &reason);
1241 reason = reason ? reason : sipmsg_get_ms_diagnostics_public_reason(msg);
1242 warning = g_strdup_printf(_("You have been rejected by the server: %s"),
1243 reason ? reason : _("no reason given"));
1244 g_free(reason);
1246 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1247 SIPE_CONNECTION_ERROR_INVALID_SETTINGS,
1248 warning);
1249 g_free(warning);
1250 return TRUE;
1252 break;
1253 case 404:
1255 const gchar *diagnostics = sipmsg_find_header(msg, "ms-diagnostics");
1256 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1257 gchar *warning;
1258 warning = g_strdup_printf(_("Not found: %s. Please contact your Administrator"),
1259 diagnostics ? (reason ? reason : _("no reason given")) :
1260 _("SIP is either not enabled for the destination URI or it does not exist"));
1261 g_free(reason);
1263 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1264 SIPE_CONNECTION_ERROR_INVALID_USERNAME,
1265 warning);
1266 g_free(warning);
1267 return TRUE;
1269 break;
1270 case 504: /* Server time-out */
1271 /* first attempt + 5 retries */
1272 if (transport->register_attempt < 6) {
1273 SIPE_DEBUG_INFO("process_register_response: RE-REGISTER timeout on attempt %d, retrying later",
1274 transport->register_attempt);
1275 sip_transport_set_reregister(sipe_private, 60);
1276 return TRUE;
1278 /* FALLTHROUGH */
1279 case 503:
1281 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1282 gchar *warning;
1283 warning = g_strdup_printf(_("Service unavailable: %s"), reason ? reason : _("no reason given"));
1284 g_free(reason);
1286 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1287 SIPE_CONNECTION_ERROR_NETWORK,
1288 warning);
1289 g_free(warning);
1290 return TRUE;
1292 break;
1294 return TRUE;
1297 static gboolean register_response_timeout(struct sipe_core_private *sipe_private,
1298 SIPE_UNUSED_PARAMETER struct sipmsg *msg,
1299 SIPE_UNUSED_PARAMETER struct transaction *trans)
1301 struct sip_transport *transport = sipe_private->transport;
1302 if (transport->register_attempt < 6) {
1303 SIPE_DEBUG_INFO("register_response_timeout: no answer to attempt %d, retrying",
1304 transport->register_attempt);
1305 do_register(sipe_private, FALSE);
1306 } else {
1307 gchar *warning = g_strdup_printf(_("Service unavailable: %s"), _("no reason given"));
1308 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1309 SIPE_CONNECTION_ERROR_NETWORK,
1310 warning);
1311 g_free(warning);
1313 return TRUE;
1316 static void do_register(struct sipe_core_private *sipe_private,
1317 gboolean deregister)
1319 struct sip_transport *transport = sipe_private->transport;
1320 char *uri;
1321 char *to;
1322 char *hdr;
1323 char *uuid;
1325 if (!sipe_private->public.sip_domain) return;
1327 if (!deregister) {
1328 if (transport->reregister_set) {
1329 transport->reregister_set = FALSE;
1330 transport->register_attempt = 1;
1331 } else {
1332 transport->register_attempt++;
1336 transport->auth_incomplete = FALSE;
1338 uuid = get_uuid(sipe_private);
1339 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"
1340 "Supported: gruu-10, adhoclist, msrtc-event-categories, com.microsoft.msrtc.presence\r\n"
1341 "Event: registration\r\n"
1342 "Allow-Events: presence\r\n"
1343 "ms-keep-alive: UAC;hop-hop=yes\r\n"
1344 "%s",
1345 sipe_backend_network_ip_address(),
1346 transport->connection->client_port,
1347 TRANSPORT_DESCRIPTOR,
1348 uuid,
1349 deregister ? "Expires: 0\r\n" : "");
1350 g_free(uuid);
1352 uri = sip_uri_from_name(sipe_private->public.sip_domain);
1353 to = sip_uri_self(sipe_private);
1354 sip_transport_request_timeout(sipe_private,
1355 "REGISTER",
1356 uri,
1358 hdr,
1360 NULL,
1361 process_register_response,
1363 deregister ? NULL : register_response_timeout);
1364 g_free(to);
1365 g_free(uri);
1366 g_free(hdr);
1368 if (deregister) {
1369 /* Make sure that all messages are pushed to the server
1370 before the connection gets shut down */
1371 SIPE_DEBUG_INFO_NOFORMAT("De-register from server. Flushing outstanding messages.");
1372 sipe_backend_transport_flush(transport->connection);
1376 void sip_transport_deregister(struct sipe_core_private *sipe_private)
1378 do_register(sipe_private, TRUE);
1381 void sip_transport_disconnect(struct sipe_core_private *sipe_private)
1383 struct sip_transport *transport = sipe_private->transport;
1385 /* transport can be NULL during connection setup */
1386 if (transport) {
1387 sipe_backend_transport_disconnect(transport->connection);
1389 sipe_auth_free(&transport->registrar);
1390 sipe_auth_free(&transport->proxy);
1392 g_free(transport->server_name);
1393 g_free(transport->server_version);
1394 g_free(transport->user_agent);
1396 while (transport->transactions)
1397 transactions_remove(sipe_private,
1398 transport->transactions->data);
1400 g_free(transport);
1403 sipe_private->transport = NULL;
1404 sipe_private->service_data = NULL;
1406 if (sipe_private->dns_query)
1407 sipe_backend_dns_query_cancel(sipe_private->dns_query);
1411 void sip_transport_authentication_completed(struct sipe_core_private *sipe_private)
1413 do_reauthenticate_cb(sipe_private, NULL);
1416 guint sip_transport_port(struct sipe_core_private *sipe_private)
1418 return sipe_private->transport->server_port;
1421 static void process_input_message(struct sipe_core_private *sipe_private,
1422 struct sipmsg *msg)
1424 struct sip_transport *transport = sipe_private->transport;
1425 gboolean notfound = FALSE;
1426 const char *method = msg->method ? msg->method : "NOT FOUND";
1428 SIPE_DEBUG_INFO("process_input_message: msg->response(%d),msg->method(%s)",
1429 msg->response, method);
1431 if (msg->response == 0) { /* request */
1432 if (sipe_strequal(method, "MESSAGE")) {
1433 process_incoming_message(sipe_private, msg);
1434 } else if (sipe_strequal(method, "NOTIFY")) {
1435 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_notify");
1436 process_incoming_notify(sipe_private, msg, TRUE, FALSE);
1437 } else if (sipe_strequal(method, "BENOTIFY")) {
1438 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_benotify");
1439 process_incoming_notify(sipe_private, msg, TRUE, TRUE);
1440 } else if (sipe_strequal(method, "INVITE")) {
1441 process_incoming_invite(sipe_private, msg);
1442 } else if (sipe_strequal(method, "REFER")) {
1443 process_incoming_refer(sipe_private, msg);
1444 } else if (sipe_strequal(method, "OPTIONS")) {
1445 process_incoming_options(sipe_private, msg);
1446 } else if (sipe_strequal(method, "INFO")) {
1447 process_incoming_info(sipe_private, msg);
1448 } else if (sipe_strequal(method, "ACK")) {
1449 /* ACK's don't need any response */
1450 } else if (sipe_strequal(method, "PRACK")) {
1451 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1452 } else if (sipe_strequal(method, "SUBSCRIBE")) {
1453 /* LCS 2005 sends us these - just respond 200 OK */
1454 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1455 } else if (sipe_strequal(method, "CANCEL")) {
1456 process_incoming_cancel(sipe_private, msg);
1457 } else if (sipe_strequal(method, "BYE")) {
1458 process_incoming_bye(sipe_private, msg);
1459 } else {
1460 sip_transport_response(sipe_private, msg, 501, "Not implemented", NULL);
1461 notfound = TRUE;
1464 } else { /* response */
1465 struct transaction *trans = transactions_find(transport, msg);
1466 if (trans) {
1467 if (msg->response < 200) {
1468 /* ignore provisional response */
1469 SIPE_DEBUG_INFO("process_input_message: got provisional (%d) response, ignoring", msg->response);
1471 /* Transaction not yet completed */
1472 trans = NULL;
1474 } else if (msg->response == 401) { /* Unauthorized */
1476 if (sipe_strequal(trans->msg->method, "REGISTER")) {
1477 /* Expected response during authentication handshake */
1478 transport->registrar.retries++;
1479 SIPE_DEBUG_INFO("process_input_message: RE-REGISTER CSeq: %d", transport->cseq);
1480 } else {
1481 gchar *resend;
1483 /* Are we registered? */
1484 if (transport->reregister_set) {
1485 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Retrying with new authentication.");
1486 sign_outgoing_message(sipe_private,
1487 trans->msg);
1488 } else {
1490 * We don't have a valid authentication at the moment.
1491 * Resend message unchanged. It will be rejected again
1492 * and hopefully by then we have a valid authentication.
1494 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Bouncing...");
1497 /* Resend request */
1498 resend = sipmsg_to_string(trans->msg);
1499 sipe_utils_message_debug("SIP", resend, NULL, TRUE);
1500 sipe_backend_transport_message(sipe_private->transport->connection, resend);
1501 g_free(resend);
1503 /* Transaction not yet completed */
1504 trans = NULL;
1507 } else if (msg->response == 407) { /* Proxy Authentication Required */
1509 if (transport->proxy.retries > 30) {
1510 SIPE_DEBUG_ERROR_NOFORMAT("process_input_message: too many proxy authentication retries. Giving up.");
1511 } else {
1512 gchar *resend, *auth;
1513 const gchar *auth_hdr;
1515 transport->proxy.retries++;
1517 /* do proxy authentication */
1518 auth_hdr = sipmsg_find_header(msg, "Proxy-Authenticate");
1519 if (auth_hdr) {
1520 guint i;
1521 transport->proxy.type = AUTH_TYPE_UNSET;
1522 for (i = 0; i < AUTH_PROTOCOLS; i++) {
1523 const gchar *protocol = auth_type_to_protocol[i];
1524 if (protocol &&
1525 !g_strncasecmp(auth_hdr, protocol, strlen(protocol))) {
1526 SIPE_DEBUG_INFO("proxy auth: type %s", protocol);
1527 transport->proxy.type = i;
1528 break;
1531 if (transport->proxy.type == AUTH_TYPE_UNSET)
1532 SIPE_DEBUG_ERROR("Unknown proxy authentication: %s", auth_hdr);
1533 fill_auth(auth_hdr, &transport->proxy);
1535 auth = auth_header(sipe_private, &transport->proxy, trans->msg);
1536 if (auth) {
1537 sipmsg_remove_header_now(trans->msg, "Proxy-Authorization");
1538 sipmsg_add_header_now_pos(trans->msg, "Proxy-Authorization", auth, 5);
1539 g_free(auth);
1542 /* resend request */
1543 resend = sipmsg_to_string(trans->msg);
1544 sipe_utils_message_debug("SIP", resend, NULL, TRUE);
1545 sipe_backend_transport_message(sipe_private->transport->connection, resend);
1546 g_free(resend);
1548 /* Transaction not yet completed */
1549 trans = NULL;
1552 } else {
1553 transport->registrar.retries = 0;
1554 transport->proxy.retries = 0;
1557 /* Is transaction completed? */
1558 if (trans) {
1559 if (trans->callback) {
1560 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: we have a transaction callback");
1561 /* call the callback to process response */
1562 (trans->callback)(sipe_private, msg, trans);
1565 SIPE_DEBUG_INFO("process_input_message: removing CSeq %d", transport->cseq);
1566 transactions_remove(sipe_private, trans);
1568 } else {
1569 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: received response to unknown transaction");
1570 notfound = TRUE;
1574 if (notfound) {
1575 SIPE_DEBUG_INFO("received a unknown sip message with method %s and response %d", method, msg->response);
1579 static void sip_transport_input(struct sipe_transport_connection *conn)
1581 struct sipe_core_private *sipe_private = conn->user_data;
1582 struct sip_transport *transport = sipe_private->transport;
1583 gchar *cur = conn->buffer;
1585 /* according to the RFC remove CRLF at the beginning */
1586 while (*cur == '\r' || *cur == '\n') {
1587 cur++;
1589 if (cur != conn->buffer)
1590 sipe_utils_shrink_buffer(conn, cur);
1592 /* Received a full Header? */
1593 transport->processing_input = TRUE;
1594 while (transport->processing_input &&
1595 ((cur = strstr(conn->buffer, "\r\n\r\n")) != NULL)) {
1596 struct sipmsg *msg;
1597 guint remainder;
1599 cur += 2;
1600 cur[0] = '\0';
1601 msg = sipmsg_parse_header(conn->buffer);
1603 cur += 2;
1604 remainder = conn->buffer_used - (cur - conn->buffer);
1605 if (msg && remainder >= (guint) msg->bodylen) {
1606 char *dummy = g_malloc(msg->bodylen + 1);
1607 memcpy(dummy, cur, msg->bodylen);
1608 dummy[msg->bodylen] = '\0';
1609 msg->body = dummy;
1610 cur += msg->bodylen;
1611 sipe_utils_message_debug("SIP",
1612 conn->buffer,
1613 msg->body,
1614 FALSE);
1615 sipe_utils_shrink_buffer(conn, cur);
1616 } else {
1617 if (msg){
1618 SIPE_DEBUG_INFO("sipe_transport_input: body too short (%d < %d, strlen %d) - ignoring message", remainder, msg->bodylen, (int)strlen(conn->buffer));
1619 sipmsg_free(msg);
1622 /* restore header for next try */
1623 cur[-2] = '\r';
1624 return;
1627 // Verify the signature before processing it
1628 if (transport->registrar.gssapi_context &&
1629 sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
1630 struct sipmsg_breakdown msgbd;
1631 gchar *signature_input_str;
1632 gchar *rspauth;
1633 msgbd.msg = msg;
1634 sipmsg_breakdown_parse(&msgbd, transport->registrar.realm, transport->registrar.target);
1635 signature_input_str = sipmsg_breakdown_get_string(transport->registrar.version, &msgbd);
1637 rspauth = sipmsg_find_part_of_header(sipmsg_find_header(msg, "Authentication-Info"), "rspauth=\"", "\"", NULL);
1639 if (rspauth != NULL) {
1640 if (!sip_sec_verify_signature(transport->registrar.gssapi_context, signature_input_str, rspauth)) {
1641 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message validated");
1642 process_input_message(sipe_private, msg);
1643 } else {
1644 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message is invalid.");
1645 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1646 SIPE_CONNECTION_ERROR_NETWORK,
1647 _("Invalid message signature received"));
1649 } else if ((msg->response == 401) ||
1650 sipe_strequal(msg->method, "REGISTER")) {
1651 /* a) Retry non-REGISTER requests with updated authentication */
1652 /* b) We must always process REGISTER responses */
1653 process_input_message(sipe_private, msg);
1654 } else {
1655 /* OCS sends provisional messages that are *not* signed */
1656 if (msg->response >= 200) {
1657 /* We are not calling process_input_message(),
1658 so we need to drop the transaction here. */
1659 struct transaction *trans = transactions_find(transport, msg);
1660 if (trans) transactions_remove(sipe_private, trans);
1662 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: message without authentication data - ignoring");
1664 g_free(signature_input_str);
1666 g_free(rspauth);
1667 sipmsg_breakdown_free(&msgbd);
1668 } else {
1669 process_input_message(sipe_private, msg);
1672 sipmsg_free(msg);
1674 /* Redirect: old content of "transport" is no longer valid */
1675 transport = sipe_private->transport;
1679 static void sip_transport_connected(struct sipe_transport_connection *conn)
1681 struct sipe_core_private *sipe_private = conn->user_data;
1682 sipe_private->service_data = NULL;
1683 do_register(sipe_private, FALSE);
1686 static void resolve_next_service(struct sipe_core_private *sipe_private,
1687 const struct sip_service_data *start);
1688 static void sip_transport_error(struct sipe_transport_connection *conn,
1689 const gchar *msg)
1691 struct sipe_core_private *sipe_private = conn->user_data;
1693 /* This failed attempt was based on a DNS SRV record */
1694 if (sipe_private->service_data) {
1695 resolve_next_service(sipe_private, NULL);
1696 } else {
1697 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1698 SIPE_CONNECTION_ERROR_NETWORK,
1699 msg);
1703 /* server_name must be g_alloc()'ed */
1704 static void sipe_server_register(struct sipe_core_private *sipe_private,
1705 guint type,
1706 gchar *server_name,
1707 guint server_port)
1709 sipe_connect_setup setup = {
1710 type,
1711 server_name,
1712 (server_port != 0) ? server_port :
1713 (type == SIPE_TRANSPORT_TLS) ? 5061 : 5060,
1714 sipe_private,
1715 sip_transport_connected,
1716 sip_transport_input,
1717 sip_transport_error
1719 struct sip_transport *transport = g_new0(struct sip_transport, 1);
1721 transport->server_name = server_name;
1722 transport->server_port = setup.server_port;
1723 transport->connection = sipe_backend_transport_connect(SIPE_CORE_PUBLIC,
1724 &setup);
1725 sipe_private->transport = transport;
1728 struct sip_service_data {
1729 const char *protocol;
1730 const char *transport;
1731 guint type;
1734 /* Service list for autodection */
1735 static const struct sip_service_data service_autodetect[] = {
1736 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1737 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1738 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1739 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1740 { NULL, NULL, 0 }
1743 /* Service list for SSL/TLS */
1744 static const struct sip_service_data service_tls[] = {
1745 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1746 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1747 { NULL, NULL, 0 }
1750 /* Service list for TCP */
1751 static const struct sip_service_data service_tcp[] = {
1752 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1753 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1754 { NULL, NULL, 0 }
1757 static const struct sip_service_data *services[] = {
1758 service_autodetect, /* SIPE_TRANSPORT_AUTO */
1759 service_tls, /* SIPE_TRANSPORT_TLS */
1760 service_tcp /* SIPE_TRANSPORT_TCP */
1763 static void sipe_core_dns_resolved(struct sipe_core_public *sipe_public,
1764 const gchar *hostname, guint port)
1766 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
1768 sipe_private->dns_query = NULL;
1770 if (hostname) {
1771 SIPE_DEBUG_INFO("sipe_core_dns_resolved - SRV hostname: %s port: %d",
1772 hostname, port);
1773 sipe_server_register(sipe_private,
1774 sipe_private->service_data->type,
1775 g_strdup(hostname), port);
1776 } else {
1777 resolve_next_service(SIPE_CORE_PRIVATE, NULL);
1781 static void resolve_next_service(struct sipe_core_private *sipe_private,
1782 const struct sip_service_data *start)
1784 if (start) {
1785 sipe_private->service_data = start;
1786 } else {
1787 sipe_private->service_data++;
1788 if (sipe_private->service_data->protocol == NULL) {
1789 guint type = sipe_private->transport_type;
1791 /* We tried all services */
1792 sipe_private->service_data = NULL;
1794 /* Try connecting to the SIP hostname directly */
1795 SIPE_DEBUG_INFO_NOFORMAT("no SRV records found; using SIP domain as fallback");
1796 if (type == SIPE_TRANSPORT_AUTO)
1797 type = SIPE_TRANSPORT_TLS;
1799 sipe_server_register(sipe_private, type,
1800 g_strdup(sipe_private->public.sip_domain),
1802 return;
1806 /* Try to resolve next service */
1807 sipe_private->dns_query = sipe_backend_dns_query_srv(
1808 sipe_private->service_data->protocol,
1809 sipe_private->service_data->transport,
1810 sipe_private->public.sip_domain,
1811 (sipe_dns_resolved_cb) sipe_core_dns_resolved,
1812 SIPE_CORE_PUBLIC);
1815 void sipe_core_transport_sip_connect(struct sipe_core_public *sipe_public,
1816 guint transport,
1817 const gchar *server,
1818 const gchar *port)
1820 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
1822 if (server) {
1823 /* Use user specified server[:port] */
1824 int port_number = 0;
1826 if (port)
1827 port_number = atoi(port);
1829 SIPE_DEBUG_INFO("sipe_core_connect: user specified SIP server %s:%d",
1830 server, port_number);
1832 sipe_server_register(sipe_private, transport,
1833 g_strdup(server), port_number);
1834 } else {
1835 /* Server auto-discovery */
1837 /* Remember user specified transport type */
1838 sipe_private->transport_type = transport;
1839 resolve_next_service(sipe_private, services[transport]);
1843 void sipe_core_transport_sip_keepalive(struct sipe_core_public *sipe_public)
1845 SIPE_DEBUG_INFO("sending keep alive %d",
1846 sipe_public->keepalive_timeout);
1847 sipe_utils_message_debug("SIP", "", NULL, TRUE);
1848 sipe_backend_transport_message(SIPE_CORE_PRIVATE->transport->connection,
1849 "\r\n\r\n");
1852 int sip_transaction_cseq(struct transaction *trans)
1854 int cseq;
1856 g_return_val_if_fail(trans && trans->key, 0);
1858 sscanf(trans->key, "<%*[a-zA-Z0-9]><%d INVITE>", &cseq);
1859 return cseq;
1863 Local Variables:
1864 mode: c
1865 c-file-style: "bsd"
1866 indent-tabs-mode: t
1867 tab-width: 8
1868 End: