tls-dsk: flesh out state transitions
[siplcs.git] / src / core / sip-transport.c
blobd5fc35e31be7d510131ce2fd2ba405d594096ee9
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.retries > 2) {
1205 SIPE_DEBUG_INFO_NOFORMAT("process_register_response: still not authenticated after 3 tries - giving up.");
1206 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1207 SIPE_CONNECTION_ERROR_AUTHENTICATION_FAILED,
1208 _("Authentication failed"));
1209 return TRUE;
1212 if (transport->reauthenticate_set) {
1213 SIPE_DEBUG_ERROR_NOFORMAT("process_register_response: RE-REGISTER rejected, triggering re-authentication");
1214 do_reauthenticate_cb(sipe_private, NULL);
1215 return TRUE;
1218 auth_hdr = get_auth_header(sipe_private, &transport->registrar, msg);
1219 if (!auth_hdr) {
1220 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1221 SIPE_CONNECTION_ERROR_AUTHENTICATION_IMPOSSIBLE,
1222 _("Incompatible authentication scheme chosen"));
1223 return TRUE;
1225 SIPE_DEBUG_INFO("process_register_response: Auth header: %s", auth_hdr);
1226 fill_auth(auth_hdr, &transport->registrar);
1227 transport->reregister_set = FALSE;
1228 transport->register_attempt = 0;
1229 do_register(sipe_private,
1230 sipe_backend_connection_is_disconnecting(SIPE_CORE_PUBLIC));
1232 break;
1233 case 403:
1235 gchar *reason;
1236 gchar *warning;
1237 sipmsg_parse_warning(msg, &reason);
1238 reason = reason ? reason : sipmsg_get_ms_diagnostics_public_reason(msg);
1239 warning = g_strdup_printf(_("You have been rejected by the server: %s"),
1240 reason ? reason : _("no reason given"));
1241 g_free(reason);
1243 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1244 SIPE_CONNECTION_ERROR_INVALID_SETTINGS,
1245 warning);
1246 g_free(warning);
1247 return TRUE;
1249 break;
1250 case 404:
1252 const gchar *diagnostics = sipmsg_find_header(msg, "ms-diagnostics");
1253 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1254 gchar *warning;
1255 warning = g_strdup_printf(_("Not found: %s. Please contact your Administrator"),
1256 diagnostics ? (reason ? reason : _("no reason given")) :
1257 _("SIP is either not enabled for the destination URI or it does not exist"));
1258 g_free(reason);
1260 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1261 SIPE_CONNECTION_ERROR_INVALID_USERNAME,
1262 warning);
1263 g_free(warning);
1264 return TRUE;
1266 break;
1267 case 504: /* Server time-out */
1268 /* first attempt + 5 retries */
1269 if (transport->register_attempt < 6) {
1270 SIPE_DEBUG_INFO("process_register_response: RE-REGISTER timeout on attempt %d, retrying later",
1271 transport->register_attempt);
1272 sip_transport_set_reregister(sipe_private, 60);
1273 return TRUE;
1275 /* FALLTHROUGH */
1276 case 503:
1278 gchar *reason = sipmsg_get_ms_diagnostics_reason(msg);
1279 gchar *warning;
1280 warning = g_strdup_printf(_("Service unavailable: %s"), reason ? reason : _("no reason given"));
1281 g_free(reason);
1283 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1284 SIPE_CONNECTION_ERROR_NETWORK,
1285 warning);
1286 g_free(warning);
1287 return TRUE;
1289 break;
1291 return TRUE;
1294 static gboolean register_response_timeout(struct sipe_core_private *sipe_private,
1295 SIPE_UNUSED_PARAMETER struct sipmsg *msg,
1296 SIPE_UNUSED_PARAMETER struct transaction *trans)
1298 struct sip_transport *transport = sipe_private->transport;
1299 if (transport->register_attempt < 6) {
1300 SIPE_DEBUG_INFO("register_response_timeout: no answer to attempt %d, retrying",
1301 transport->register_attempt);
1302 do_register(sipe_private, FALSE);
1303 } else {
1304 gchar *warning = g_strdup_printf(_("Service unavailable: %s"), _("no reason given"));
1305 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1306 SIPE_CONNECTION_ERROR_NETWORK,
1307 warning);
1308 g_free(warning);
1310 return TRUE;
1313 static void do_register(struct sipe_core_private *sipe_private,
1314 gboolean deregister)
1316 struct sip_transport *transport = sipe_private->transport;
1317 char *uri;
1318 char *to;
1319 char *hdr;
1320 char *uuid;
1322 if (!sipe_private->public.sip_domain) return;
1324 if (!deregister) {
1325 if (transport->reregister_set) {
1326 transport->reregister_set = FALSE;
1327 transport->register_attempt = 1;
1328 } else {
1329 transport->register_attempt++;
1333 transport->auth_incomplete = FALSE;
1335 uuid = get_uuid(sipe_private);
1336 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"
1337 "Supported: gruu-10, adhoclist, msrtc-event-categories, com.microsoft.msrtc.presence\r\n"
1338 "Event: registration\r\n"
1339 "Allow-Events: presence\r\n"
1340 "ms-keep-alive: UAC;hop-hop=yes\r\n"
1341 "%s",
1342 sipe_backend_network_ip_address(),
1343 transport->connection->client_port,
1344 TRANSPORT_DESCRIPTOR,
1345 uuid,
1346 deregister ? "Expires: 0\r\n" : "");
1347 g_free(uuid);
1349 uri = sip_uri_from_name(sipe_private->public.sip_domain);
1350 to = sip_uri_self(sipe_private);
1351 sip_transport_request_timeout(sipe_private,
1352 "REGISTER",
1353 uri,
1355 hdr,
1357 NULL,
1358 process_register_response,
1360 deregister ? NULL : register_response_timeout);
1361 g_free(to);
1362 g_free(uri);
1363 g_free(hdr);
1365 if (deregister) {
1366 /* Make sure that all messages are pushed to the server
1367 before the connection gets shut down */
1368 SIPE_DEBUG_INFO_NOFORMAT("De-register from server. Flushing outstanding messages.");
1369 sipe_backend_transport_flush(transport->connection);
1373 void sip_transport_deregister(struct sipe_core_private *sipe_private)
1375 do_register(sipe_private, TRUE);
1378 void sip_transport_disconnect(struct sipe_core_private *sipe_private)
1380 struct sip_transport *transport = sipe_private->transport;
1382 /* transport can be NULL during connection setup */
1383 if (transport) {
1384 sipe_backend_transport_disconnect(transport->connection);
1386 sipe_auth_free(&transport->registrar);
1387 sipe_auth_free(&transport->proxy);
1389 g_free(transport->server_name);
1390 g_free(transport->server_version);
1391 g_free(transport->user_agent);
1393 while (transport->transactions)
1394 transactions_remove(sipe_private,
1395 transport->transactions->data);
1397 g_free(transport);
1400 sipe_private->transport = NULL;
1401 sipe_private->service_data = NULL;
1403 if (sipe_private->dns_query)
1404 sipe_backend_dns_query_cancel(sipe_private->dns_query);
1408 void sip_transport_authentication_completed(struct sipe_core_private *sipe_private)
1410 do_reauthenticate_cb(sipe_private, NULL);
1413 guint sip_transport_port(struct sipe_core_private *sipe_private)
1415 return sipe_private->transport->server_port;
1418 static void process_input_message(struct sipe_core_private *sipe_private,
1419 struct sipmsg *msg)
1421 struct sip_transport *transport = sipe_private->transport;
1422 gboolean notfound = FALSE;
1423 const char *method = msg->method ? msg->method : "NOT FOUND";
1425 SIPE_DEBUG_INFO("process_input_message: msg->response(%d),msg->method(%s)",
1426 msg->response, method);
1428 if (msg->response == 0) { /* request */
1429 if (sipe_strequal(method, "MESSAGE")) {
1430 process_incoming_message(sipe_private, msg);
1431 } else if (sipe_strequal(method, "NOTIFY")) {
1432 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_notify");
1433 process_incoming_notify(sipe_private, msg, TRUE, FALSE);
1434 } else if (sipe_strequal(method, "BENOTIFY")) {
1435 SIPE_DEBUG_INFO_NOFORMAT("send->process_incoming_benotify");
1436 process_incoming_notify(sipe_private, msg, TRUE, TRUE);
1437 } else if (sipe_strequal(method, "INVITE")) {
1438 process_incoming_invite(sipe_private, msg);
1439 } else if (sipe_strequal(method, "REFER")) {
1440 process_incoming_refer(sipe_private, msg);
1441 } else if (sipe_strequal(method, "OPTIONS")) {
1442 process_incoming_options(sipe_private, msg);
1443 } else if (sipe_strequal(method, "INFO")) {
1444 process_incoming_info(sipe_private, msg);
1445 } else if (sipe_strequal(method, "ACK")) {
1446 /* ACK's don't need any response */
1447 } else if (sipe_strequal(method, "PRACK")) {
1448 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1449 } else if (sipe_strequal(method, "SUBSCRIBE")) {
1450 /* LCS 2005 sends us these - just respond 200 OK */
1451 sip_transport_response(sipe_private, msg, 200, "OK", NULL);
1452 } else if (sipe_strequal(method, "CANCEL")) {
1453 process_incoming_cancel(sipe_private, msg);
1454 } else if (sipe_strequal(method, "BYE")) {
1455 process_incoming_bye(sipe_private, msg);
1456 } else {
1457 sip_transport_response(sipe_private, msg, 501, "Not implemented", NULL);
1458 notfound = TRUE;
1461 } else { /* response */
1462 struct transaction *trans = transactions_find(transport, msg);
1463 if (trans) {
1464 if (msg->response < 200) {
1465 /* ignore provisional response */
1466 SIPE_DEBUG_INFO("process_input_message: got provisional (%d) response, ignoring", msg->response);
1468 /* Transaction not yet completed */
1469 trans = NULL;
1471 } else if (msg->response == 401) { /* Unauthorized */
1473 if (sipe_strequal(trans->msg->method, "REGISTER")) {
1474 /* Expected response during authentication handshake */
1475 transport->registrar.retries++;
1476 SIPE_DEBUG_INFO("process_input_message: RE-REGISTER CSeq: %d", transport->cseq);
1477 } else {
1478 gchar *resend;
1480 /* Are we registered? */
1481 if (transport->reregister_set) {
1482 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Retrying with new authentication.");
1483 sign_outgoing_message(sipe_private,
1484 trans->msg);
1485 } else {
1487 * We don't have a valid authentication at the moment.
1488 * Resend message unchanged. It will be rejected again
1489 * and hopefully by then we have a valid authentication.
1491 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: 401 response to non-REGISTER message. Bouncing...");
1494 /* Resend request */
1495 resend = sipmsg_to_string(trans->msg);
1496 sipe_utils_message_debug("SIP", resend, NULL, TRUE);
1497 sipe_backend_transport_message(sipe_private->transport->connection, resend);
1498 g_free(resend);
1500 /* Transaction not yet completed */
1501 trans = NULL;
1504 } else if (msg->response == 407) { /* Proxy Authentication Required */
1506 if (transport->proxy.retries > 30) {
1507 SIPE_DEBUG_ERROR_NOFORMAT("process_input_message: too many proxy authentication retries. Giving up.");
1508 } else {
1509 gchar *resend, *auth;
1510 const gchar *auth_hdr;
1512 transport->proxy.retries++;
1514 /* do proxy authentication */
1515 auth_hdr = sipmsg_find_header(msg, "Proxy-Authenticate");
1516 if (auth_hdr) {
1517 guint i;
1518 transport->proxy.type = AUTH_TYPE_UNSET;
1519 for (i = 0; i < AUTH_PROTOCOLS; i++) {
1520 const gchar *protocol = auth_type_to_protocol[i];
1521 if (protocol &&
1522 !g_strncasecmp(auth_hdr, protocol, strlen(protocol))) {
1523 SIPE_DEBUG_INFO("proxy auth: type %s", protocol);
1524 transport->proxy.type = i;
1525 break;
1528 if (transport->proxy.type == AUTH_TYPE_UNSET)
1529 SIPE_DEBUG_ERROR("Unknown proxy authentication: %s", auth_hdr);
1530 fill_auth(auth_hdr, &transport->proxy);
1532 auth = auth_header(sipe_private, &transport->proxy, trans->msg);
1533 if (auth) {
1534 sipmsg_remove_header_now(trans->msg, "Proxy-Authorization");
1535 sipmsg_add_header_now_pos(trans->msg, "Proxy-Authorization", auth, 5);
1536 g_free(auth);
1539 /* resend request */
1540 resend = sipmsg_to_string(trans->msg);
1541 sipe_utils_message_debug("SIP", resend, NULL, TRUE);
1542 sipe_backend_transport_message(sipe_private->transport->connection, resend);
1543 g_free(resend);
1545 /* Transaction not yet completed */
1546 trans = NULL;
1549 } else {
1550 transport->registrar.retries = 0;
1551 transport->proxy.retries = 0;
1554 /* Is transaction completed? */
1555 if (trans) {
1556 if (trans->callback) {
1557 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: we have a transaction callback");
1558 /* call the callback to process response */
1559 (trans->callback)(sipe_private, msg, trans);
1562 SIPE_DEBUG_INFO("process_input_message: removing CSeq %d", transport->cseq);
1563 transactions_remove(sipe_private, trans);
1565 } else {
1566 SIPE_DEBUG_INFO_NOFORMAT("process_input_message: received response to unknown transaction");
1567 notfound = TRUE;
1571 if (notfound) {
1572 SIPE_DEBUG_INFO("received a unknown sip message with method %s and response %d", method, msg->response);
1576 static void sip_transport_input(struct sipe_transport_connection *conn)
1578 struct sipe_core_private *sipe_private = conn->user_data;
1579 struct sip_transport *transport = sipe_private->transport;
1580 gchar *cur = conn->buffer;
1582 /* according to the RFC remove CRLF at the beginning */
1583 while (*cur == '\r' || *cur == '\n') {
1584 cur++;
1586 if (cur != conn->buffer)
1587 sipe_utils_shrink_buffer(conn, cur);
1589 /* Received a full Header? */
1590 transport->processing_input = TRUE;
1591 while (transport->processing_input &&
1592 ((cur = strstr(conn->buffer, "\r\n\r\n")) != NULL)) {
1593 struct sipmsg *msg;
1594 guint remainder;
1596 cur += 2;
1597 cur[0] = '\0';
1598 msg = sipmsg_parse_header(conn->buffer);
1600 cur += 2;
1601 remainder = conn->buffer_used - (cur - conn->buffer);
1602 if (msg && remainder >= (guint) msg->bodylen) {
1603 char *dummy = g_malloc(msg->bodylen + 1);
1604 memcpy(dummy, cur, msg->bodylen);
1605 dummy[msg->bodylen] = '\0';
1606 msg->body = dummy;
1607 cur += msg->bodylen;
1608 sipe_utils_message_debug("SIP",
1609 conn->buffer,
1610 msg->body,
1611 FALSE);
1612 sipe_utils_shrink_buffer(conn, cur);
1613 } else {
1614 if (msg){
1615 SIPE_DEBUG_INFO("sipe_transport_input: body too short (%d < %d, strlen %d) - ignoring message", remainder, msg->bodylen, (int)strlen(conn->buffer));
1616 sipmsg_free(msg);
1619 /* restore header for next try */
1620 cur[-2] = '\r';
1621 return;
1624 // Verify the signature before processing it
1625 if (transport->registrar.gssapi_context &&
1626 sip_sec_context_is_ready(transport->registrar.gssapi_context)) {
1627 struct sipmsg_breakdown msgbd;
1628 gchar *signature_input_str;
1629 gchar *rspauth;
1630 msgbd.msg = msg;
1631 sipmsg_breakdown_parse(&msgbd, transport->registrar.realm, transport->registrar.target);
1632 signature_input_str = sipmsg_breakdown_get_string(transport->registrar.version, &msgbd);
1634 rspauth = sipmsg_find_part_of_header(sipmsg_find_header(msg, "Authentication-Info"), "rspauth=\"", "\"", NULL);
1636 if (rspauth != NULL) {
1637 if (!sip_sec_verify_signature(transport->registrar.gssapi_context, signature_input_str, rspauth)) {
1638 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message validated");
1639 process_input_message(sipe_private, msg);
1640 } else {
1641 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: signature of incoming message is invalid.");
1642 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1643 SIPE_CONNECTION_ERROR_NETWORK,
1644 _("Invalid message signature received"));
1646 } else if ((msg->response == 401) ||
1647 sipe_strequal(msg->method, "REGISTER")) {
1648 /* a) Retry non-REGISTER requests with updated authentication */
1649 /* b) We must always process REGISTER responses */
1650 process_input_message(sipe_private, msg);
1651 } else {
1652 /* OCS sends provisional messages that are *not* signed */
1653 if (msg->response >= 200) {
1654 /* We are not calling process_input_message(),
1655 so we need to drop the transaction here. */
1656 struct transaction *trans = transactions_find(transport, msg);
1657 if (trans) transactions_remove(sipe_private, trans);
1659 SIPE_DEBUG_INFO_NOFORMAT("sip_transport_input: message without authentication data - ignoring");
1661 g_free(signature_input_str);
1663 g_free(rspauth);
1664 sipmsg_breakdown_free(&msgbd);
1665 } else {
1666 process_input_message(sipe_private, msg);
1669 sipmsg_free(msg);
1671 /* Redirect: old content of "transport" is no longer valid */
1672 transport = sipe_private->transport;
1676 static void sip_transport_connected(struct sipe_transport_connection *conn)
1678 struct sipe_core_private *sipe_private = conn->user_data;
1679 sipe_private->service_data = NULL;
1680 do_register(sipe_private, FALSE);
1683 static void resolve_next_service(struct sipe_core_private *sipe_private,
1684 const struct sip_service_data *start);
1685 static void sip_transport_error(struct sipe_transport_connection *conn,
1686 const gchar *msg)
1688 struct sipe_core_private *sipe_private = conn->user_data;
1690 /* This failed attempt was based on a DNS SRV record */
1691 if (sipe_private->service_data) {
1692 resolve_next_service(sipe_private, NULL);
1693 } else {
1694 sipe_backend_connection_error(SIPE_CORE_PUBLIC,
1695 SIPE_CONNECTION_ERROR_NETWORK,
1696 msg);
1700 /* server_name must be g_alloc()'ed */
1701 static void sipe_server_register(struct sipe_core_private *sipe_private,
1702 guint type,
1703 gchar *server_name,
1704 guint server_port)
1706 sipe_connect_setup setup = {
1707 type,
1708 server_name,
1709 (server_port != 0) ? server_port :
1710 (type == SIPE_TRANSPORT_TLS) ? 5061 : 5060,
1711 sipe_private,
1712 sip_transport_connected,
1713 sip_transport_input,
1714 sip_transport_error
1716 struct sip_transport *transport = g_new0(struct sip_transport, 1);
1718 transport->server_name = server_name;
1719 transport->server_port = setup.server_port;
1720 transport->connection = sipe_backend_transport_connect(SIPE_CORE_PUBLIC,
1721 &setup);
1722 sipe_private->transport = transport;
1725 struct sip_service_data {
1726 const char *protocol;
1727 const char *transport;
1728 guint type;
1731 /* Service list for autodection */
1732 static const struct sip_service_data service_autodetect[] = {
1733 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1734 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1735 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1736 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1737 { NULL, NULL, 0 }
1740 /* Service list for SSL/TLS */
1741 static const struct sip_service_data service_tls[] = {
1742 { "sipinternaltls", "tcp", SIPE_TRANSPORT_TLS }, /* for internal TLS connections */
1743 { "sip", "tls", SIPE_TRANSPORT_TLS }, /* for external TLS connections */
1744 { NULL, NULL, 0 }
1747 /* Service list for TCP */
1748 static const struct sip_service_data service_tcp[] = {
1749 { "sipinternal", "tcp", SIPE_TRANSPORT_TCP }, /* for internal TCP connections */
1750 { "sip", "tcp", SIPE_TRANSPORT_TCP }, /*.for external TCP connections */
1751 { NULL, NULL, 0 }
1754 static const struct sip_service_data *services[] = {
1755 service_autodetect, /* SIPE_TRANSPORT_AUTO */
1756 service_tls, /* SIPE_TRANSPORT_TLS */
1757 service_tcp /* SIPE_TRANSPORT_TCP */
1760 static void sipe_core_dns_resolved(struct sipe_core_public *sipe_public,
1761 const gchar *hostname, guint port)
1763 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
1765 sipe_private->dns_query = NULL;
1767 if (hostname) {
1768 SIPE_DEBUG_INFO("sipe_core_dns_resolved - SRV hostname: %s port: %d",
1769 hostname, port);
1770 sipe_server_register(sipe_private,
1771 sipe_private->service_data->type,
1772 g_strdup(hostname), port);
1773 } else {
1774 resolve_next_service(SIPE_CORE_PRIVATE, NULL);
1778 static void resolve_next_service(struct sipe_core_private *sipe_private,
1779 const struct sip_service_data *start)
1781 if (start) {
1782 sipe_private->service_data = start;
1783 } else {
1784 sipe_private->service_data++;
1785 if (sipe_private->service_data->protocol == NULL) {
1786 guint type = sipe_private->transport_type;
1788 /* We tried all services */
1789 sipe_private->service_data = NULL;
1791 /* Try connecting to the SIP hostname directly */
1792 SIPE_DEBUG_INFO_NOFORMAT("no SRV records found; using SIP domain as fallback");
1793 if (type == SIPE_TRANSPORT_AUTO)
1794 type = SIPE_TRANSPORT_TLS;
1796 sipe_server_register(sipe_private, type,
1797 g_strdup(sipe_private->public.sip_domain),
1799 return;
1803 /* Try to resolve next service */
1804 sipe_private->dns_query = sipe_backend_dns_query_srv(
1805 sipe_private->service_data->protocol,
1806 sipe_private->service_data->transport,
1807 sipe_private->public.sip_domain,
1808 (sipe_dns_resolved_cb) sipe_core_dns_resolved,
1809 SIPE_CORE_PUBLIC);
1812 void sipe_core_transport_sip_connect(struct sipe_core_public *sipe_public,
1813 guint transport,
1814 const gchar *server,
1815 const gchar *port)
1817 struct sipe_core_private *sipe_private = SIPE_CORE_PRIVATE;
1819 if (server) {
1820 /* Use user specified server[:port] */
1821 int port_number = 0;
1823 if (port)
1824 port_number = atoi(port);
1826 SIPE_DEBUG_INFO("sipe_core_connect: user specified SIP server %s:%d",
1827 server, port_number);
1829 sipe_server_register(sipe_private, transport,
1830 g_strdup(server), port_number);
1831 } else {
1832 /* Server auto-discovery */
1834 /* Remember user specified transport type */
1835 sipe_private->transport_type = transport;
1836 resolve_next_service(sipe_private, services[transport]);
1840 void sipe_core_transport_sip_keepalive(struct sipe_core_public *sipe_public)
1842 SIPE_DEBUG_INFO("sending keep alive %d",
1843 sipe_public->keepalive_timeout);
1844 sipe_utils_message_debug("SIP", "", NULL, TRUE);
1845 sipe_backend_transport_message(SIPE_CORE_PRIVATE->transport->connection,
1846 "\r\n\r\n");
1849 int sip_transaction_cseq(struct transaction *trans)
1851 int cseq;
1853 g_return_val_if_fail(trans && trans->key, 0);
1855 sscanf(trans->key, "<%*[a-zA-Z0-9]><%d INVITE>", &cseq);
1856 return cseq;
1860 Local Variables:
1861 mode: c
1862 c-file-style: "bsd"
1863 indent-tabs-mode: t
1864 tab-width: 8
1865 End: