digest: add support for OpenSSL 1.1.0
[siplcs.git] / src / core / sipe-utils.c
blob43ff327ded17055fb33acea16b4c11a6a959f103
1 /**
2 * @file sipe-utils.c
4 * pidgin-sipe
6 * Copyright (C) 2009-2016 SIPE Project <http://sipe.sourceforge.net/>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <time.h>
29 #include <glib.h>
31 #include "sip-transport.h"
32 #include "sipe-backend.h"
33 #include "sipe-core.h" /* to ensure same API for backends */
34 #include "sipe-core-private.h"
35 #include "sipe-utils.h"
36 #include "uuid.h"
38 /* Generate 16 random bits */
39 #define RANDOM16BITS (rand() & 0xFFFF)
41 gchar *gencallid(void)
43 return g_strdup_printf("%04Xg%04Xa%04Xi%04Xm%04Xt%04Xb%04Xx%04Xx",
44 RANDOM16BITS, RANDOM16BITS, RANDOM16BITS,
45 RANDOM16BITS, RANDOM16BITS, RANDOM16BITS,
46 RANDOM16BITS, RANDOM16BITS);
49 gchar *gentag(void)
51 return g_strdup_printf("%04d%04d", RANDOM16BITS, RANDOM16BITS);
54 gchar *genconfid(void)
56 return g_strdup_printf("%04X%04X%04X%04X%04X%04X%04X%04X",
57 RANDOM16BITS, RANDOM16BITS, RANDOM16BITS,
58 RANDOM16BITS, RANDOM16BITS, RANDOM16BITS,
59 RANDOM16BITS, RANDOM16BITS);
62 gchar *get_contact(const struct sipe_core_private *sipe_private)
64 return g_strdup(sipe_private->contact);
67 gchar *parse_from(const gchar *hdr)
69 gchar *from;
70 const gchar *tmp, *tmp2 = hdr;
72 if (!hdr) return NULL;
73 SIPE_DEBUG_INFO("parsing address out of %s", hdr);
74 tmp = strchr(hdr, '<');
76 /* i hate the different SIP UA behaviours... */
77 if (tmp) { /* sip address in <...> */
78 tmp2 = tmp + 1;
79 tmp = strchr(tmp2, '>');
80 if (tmp) {
81 from = g_strndup(tmp2, tmp - tmp2);
82 } else {
83 SIPE_DEBUG_INFO_NOFORMAT("found < without > in From");
84 return NULL;
86 } else {
87 tmp = strchr(tmp2, ';');
88 if (tmp) {
89 from = g_strndup(tmp2, tmp - tmp2);
90 } else {
91 from = g_strdup(tmp2);
94 SIPE_DEBUG_INFO("got %s", from);
95 return from;
98 gchar *sip_uri_from_name(const gchar *name)
100 return(g_strdup_printf("sip:%s", name));
103 gchar *sip_uri(const gchar *string)
105 return(strstr(string, "sip:") ? g_strdup(string) : sip_uri_from_name(string));
108 static gchar *escape_uri_part(const gchar *in, guint len)
110 gchar *escaped = NULL;
112 if (len) {
113 gchar *s;
115 /* reserve space for worst case, i.e. every character needs escaping */
116 escaped = s = g_malloc(3 * len + 1);
117 while (len--) {
118 gchar c = *in++;
120 /* only allow ASCII characters */
121 if (!isascii(c)) {
122 g_free(escaped);
123 return(NULL);
127 * RFC 3986 Appendix A
129 * authority = [ userinfo "@" ] host [ ":" port ]
130 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
131 * host = IP-literal / IPv4address / reg-name
132 * reg-name = *( unreserved / pct-encoded / sub-delims )
133 * pct-encoded = "%" HEXDIG HEXDIG
134 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
136 * Escape everything that isn't in "unreserved"
138 if (isalnum(c) ||
139 (c == '.') ||
140 (c == '-') ||
141 (c == '_') ||
142 (c == '~')) {
143 *s++ = c;
144 } else {
145 sprintf(s, "%%%1X%1X", c / 16, c % 16);
146 s += 3;
149 *s = '\0';
152 return(escaped);
155 gchar *sip_uri_if_valid(const gchar *string)
157 /* strip possible sip: prefix */
158 const gchar *uri = sipe_get_no_sip_uri(string);
159 const gchar *at;
160 gchar *result = NULL;
162 /* only XXX@YYY is valid */
163 if (uri && ((at = strchr(uri, '@')) != NULL)) {
164 gchar *userinfo = escape_uri_part(uri, at - uri);
166 if (userinfo) {
167 gchar *host = escape_uri_part(at + 1, strlen(at + 1));
169 if (host) {
170 /* name is valid for URI, convert it */
171 result = g_strdup_printf("sip:%s@%s",
172 userinfo,
173 host);
174 g_free(host);
176 g_free(userinfo);
180 return(result);
183 const gchar *sipe_get_no_sip_uri(const gchar *sip_uri)
185 #define SIP_PREFIX "sip:"
187 if (!sip_uri) return NULL;
189 if (g_str_has_prefix(sip_uri, SIP_PREFIX)) {
190 return(sip_uri + strlen(SIP_PREFIX));
191 } else {
192 return sip_uri;
196 gchar *get_uuid(struct sipe_core_private *sipe_private)
198 return(generateUUIDfromEPID(sip_transport_epid(sipe_private)));
202 guint
203 sipe_get_pub_instance(struct sipe_core_private *sipe_private,
204 int publication_key)
206 unsigned res = 0;
208 sscanf(sip_transport_epid(sipe_private), "%08x", &res);
210 if (publication_key == SIPE_PUB_DEVICE) {
211 /* as is */
212 } else if (publication_key == SIPE_PUB_STATE_MACHINE) { /* First hexadecimal digit is 0x3 */
213 res = (res >> 4) | 0x30000000;
214 } else if (publication_key == SIPE_PUB_STATE_USER) {
215 res = 0x20000000; /* fixed */
216 } else if (publication_key == SIPE_PUB_STATE_CALENDAR) { /* First hexadecimal digit is 0x4 */
217 res = (res >> 4) | 0x40000000;
218 } else if (publication_key == SIPE_PUB_STATE_CALENDAR_OOF) { /* First hexadecimal digit is 0x5 */
219 res = (res >> 4) | 0x50000000;
220 } else if (publication_key == SIPE_PUB_CALENDAR_DATA ||
221 publication_key == SIPE_PUB_NOTE_OOF)
222 { /* First hexadecimal digit is 0x4 */
223 unsigned calendar_id = 0;
224 char *mail_hash = sipe_get_epid(sipe_private->email, "", "");
226 sscanf(mail_hash, "%08x", &calendar_id);
227 g_free(mail_hash);
228 res = (calendar_id >> 4) | 0x40000000;
229 } else if (publication_key == SIPE_PUB_STATE_PHONE_VOIP) { /* First hexadecimal digit is 0x8 */
230 res = (res >> 4) | 0x80000000;
233 return res;
236 gboolean
237 sipe_is_bad_alias(const char *uri,
238 const char *alias)
240 char *uri_alias;
241 gboolean result = FALSE;
243 if (!uri) return FALSE;
244 if (!alias) return TRUE;
246 if (g_str_has_prefix(alias, "sip:") || g_str_has_prefix(alias, "sips:")) return TRUE;
248 /* check if alias is just SIP URI but without 'sip:' prefix */
249 uri_alias = sip_uri_from_name(alias);
250 if (sipe_strcase_equal(uri, uri_alias)) {
251 result = TRUE;
253 g_free(uri_alias);
255 return result;
258 gboolean
259 is_empty(const char *st)
261 if (!st || strlen(st) == 0)
263 return TRUE;
265 /* suspicious leading or trailing spaces */
266 else if (isspace((unsigned char) *st) ||
267 isspace((unsigned char) *(st + strlen(st) - 1)))
269 /* to not modify original string */
270 char *dup = g_strdup(st);
271 if (strlen(g_strstrip(dup)) == 0) {
272 g_free(dup);
273 return TRUE;
275 g_free(dup);
277 return FALSE;
280 void sipe_utils_message_debug(const gchar *type,
281 const gchar *header,
282 const gchar *body,
283 gboolean sending)
285 if (sipe_backend_debug_enabled()) {
286 GString *str = g_string_new("");
287 GTimeVal currtime;
288 gchar *time_str;
289 const char *marker = sending ?
290 ">>>>>>>>>>" :
291 "<<<<<<<<<<";
292 gchar *tmp;
294 g_get_current_time(&currtime);
295 time_str = g_time_val_to_iso8601(&currtime);
296 g_string_append_printf(str, "\nMESSAGE START %s %s - %s\n", marker, type, time_str);
297 g_string_append(str, tmp = sipe_utils_str_replace(header, "\r\n", "\n"));
298 g_free(tmp);
299 g_string_append(str, "\n");
300 if (body) {
301 g_string_append(str, tmp = sipe_utils_str_replace(body, "\r\n", "\n"));
302 g_free(tmp);
303 g_string_append(str, "\n");
305 g_string_append_printf(str, "MESSAGE END %s %s - %s", marker, type, time_str);
306 g_free(time_str);
307 SIPE_DEBUG_INFO_NOFORMAT(str->str);
308 g_string_free(str, TRUE);
312 gboolean
313 sipe_strequal(const gchar *left, const gchar *right)
315 #if GLIB_CHECK_VERSION(2,16,0)
316 return (g_strcmp0(left, right) == 0);
317 #else
318 return ((left == NULL && right == NULL) ||
319 (left != NULL && right != NULL && strcmp(left, right) == 0));
320 #endif
323 gboolean
324 sipe_strcase_equal(const gchar *left, const gchar *right)
326 return ((left == NULL && right == NULL) ||
327 (left != NULL && right != NULL && g_ascii_strcasecmp(left, right) == 0));
330 gint sipe_strcompare(gconstpointer a, gconstpointer b)
332 #if GLIB_CHECK_VERSION(2,16,0)
333 return (g_strcmp0(a, b));
334 #else
335 if (!a)
336 return -(a != b);
337 if (!b)
338 return a != b;
339 return strcmp(a, b);
340 #endif
343 time_t
344 sipe_utils_str_to_time(const gchar *timestamp)
346 GTimeVal time;
347 gboolean success = FALSE;
349 /* g_time_val_from_iso8601() warns about NULL pointer */
350 if (timestamp) {
351 guint len;
353 /* We have to make sure that the ISO8601 contains a time zone offset,
354 otherwise the time is interpreted as local time, not UTC!
355 @TODO: is there a better way to check this? */
356 if (((len = strlen(timestamp)) > 0) &&
357 isdigit(timestamp[len-1])) {
358 gchar *tmp = g_strdup_printf("%sZ", timestamp);
359 success = g_time_val_from_iso8601(tmp, &time);
360 g_free(tmp);
361 } else {
362 success = g_time_val_from_iso8601(timestamp, &time);
366 if (!success) {
367 SIPE_DEBUG_ERROR("sipe_utils_str_to_time: failed to parse ISO8601 string '%s'",
368 timestamp ? timestamp : "");
369 time.tv_sec = 0;
372 return time.tv_sec;
375 gchar *
376 sipe_utils_time_to_str(time_t timestamp)
378 GTimeVal time = { timestamp, 0 };
379 return g_time_val_to_iso8601(&time);
382 const gchar *sipe_utils_time_to_debug_str(const struct tm *tm)
384 gchar *buffer = asctime(tm);
385 size_t length;
387 if (!buffer)
388 return("");
390 /* asctime() appends "\n" to the resulting string -> strip it */
391 length = strlen(buffer);
392 if (length)
393 buffer[length - 1] = '\0';
395 return(buffer);
398 size_t
399 hex_str_to_buff(const char *hex_str, guint8 **buff)
401 char two_digits[3];
402 size_t length;
403 size_t i;
405 if (!buff) return 0;
406 if (!hex_str) return 0;
408 length = strlen(hex_str)/2;
409 *buff = (unsigned char *)g_malloc(length);
410 for (i = 0; i < length; i++) {
411 two_digits[0] = hex_str[i * 2];
412 two_digits[1] = hex_str[i * 2 + 1];
413 two_digits[2] = '\0';
414 (*buff)[i] = (unsigned char)strtoul(two_digits, NULL, 16);
417 return length;
420 char *
421 buff_to_hex_str(const guint8 *buff, const size_t buff_len)
423 char *res;
424 size_t i, j;
426 if (!buff) return NULL;
428 res = g_malloc(buff_len * 2 + 1);
429 for (i = 0, j = 0; i < buff_len; i++, j+=2) {
430 sprintf(&res[j], "%02X", buff[i]);
432 res[j] = '\0';
433 return res;
436 gboolean
437 sipe_utils_parse_lines(GSList **list, gchar **lines, gchar *delimiter)
439 int i;
440 gchar **parts;
441 gchar *dummy;
442 gchar *dummy2;
443 gchar *tmp;
445 for(i = 0; lines[i] && strlen(lines[i]) > 2; i++) {
446 parts = g_strsplit(lines[i], delimiter, 2);
447 if(!parts[0] || !parts[1]) {
448 g_strfreev(parts);
449 return FALSE;
451 dummy = parts[1];
452 dummy2 = 0;
453 while(*dummy==' ' || *dummy=='\t') dummy++;
454 dummy2 = g_strdup(dummy);
455 while(lines[i+1] && (lines[i+1][0]==' ' || lines[i+1][0]=='\t')) {
456 i++;
457 dummy = lines[i];
458 while(*dummy==' ' || *dummy=='\t') dummy++;
459 tmp = g_strdup_printf("%s %s",dummy2, dummy);
460 g_free(dummy2);
461 dummy2 = tmp;
463 *list = sipe_utils_nameval_add(*list, parts[0], dummy2);
464 g_free(dummy2);
465 g_strfreev(parts);
468 return TRUE;
471 GSList*
472 sipe_utils_nameval_add(GSList* list, const gchar *name, const gchar *value)
474 struct sipnameval *element = g_new0(struct sipnameval,1);
476 /* SANITY CHECK: the calling code must be fixed if this happens! */
477 if (!value) {
478 SIPE_DEBUG_ERROR("sipe_utils_nameval_add: NULL value for %s",
479 name);
480 value = "";
483 element->name = g_strdup(name);
484 element->value = g_strdup(value);
485 return g_slist_append(list, element);
488 void
489 sipe_utils_nameval_free(GSList *list) {
490 struct sipnameval *elem;
491 while(list) {
492 elem = list->data;
493 list = g_slist_remove(list,elem);
494 g_free(elem->name);
495 g_free(elem->value);
496 g_free(elem);
500 const gchar *
501 sipe_utils_nameval_find(const GSList *list, const gchar *name)
503 return sipe_utils_nameval_find_instance (list, name, 0);
506 const gchar *
507 sipe_utils_nameval_find_instance(const GSList *list, const gchar *name, int which)
509 const GSList *tmp;
510 struct sipnameval *elem;
511 int i = 0;
512 tmp = list;
513 while(tmp) {
514 elem = tmp->data;
515 // OCS2005 can send the same header in either all caps or mixed case
516 if (sipe_strcase_equal(elem->name, name)) {
517 if (i == which) {
518 return elem->value;
520 i++;
522 tmp = g_slist_next(tmp);
524 return NULL;
527 gchar *sipe_utils_str_replace(const gchar *string,
528 const gchar *delimiter,
529 const gchar *replacement)
531 gchar **split;
532 gchar *result;
534 if (!string || !delimiter || !replacement) return NULL;
536 split = g_strsplit(string, delimiter, 0);
537 result = g_strjoinv(replacement, split);
538 g_strfreev(split);
540 return result;
543 void sipe_utils_shrink_buffer(struct sipe_transport_connection *conn,
544 const gchar *unread)
546 conn->buffer_used -= unread - conn->buffer;
547 /* string terminator is not included in buffer_used */
548 memmove(conn->buffer, unread, conn->buffer_used + 1);
551 gboolean sipe_utils_ip_is_private(const char *ip)
553 return g_str_has_prefix(ip, "10.") ||
554 g_str_has_prefix(ip, "172.16.") ||
555 g_str_has_prefix(ip, "192.168.");
558 gchar *sipe_utils_presence_key(const gchar *uri)
560 return g_strdup_printf("<presence><%s>", uri);
563 gchar *
564 sipe_utils_uri_unescape(const gchar *string)
566 gchar *unescaped;
567 gchar *tmp;
569 if (!string)
570 return NULL;
572 #if GLIB_CHECK_VERSION(2,16,0)
573 unescaped = g_uri_unescape_string(string, NULL);
574 #else
575 // based on libpurple/util.c:purple_url_decode()
577 GString *buf = g_string_new(NULL);
578 size_t len = strlen(string);
579 char hex[3];
581 hex[2] = '\0';
583 while (len--) {
584 gchar c = *string++;
586 if ((len >= 2) && (c == '%')) {
587 strncpy(hex, string, 2);
588 c = strtol(hex, NULL, 16);
590 string += 2;
591 len -= 2;
594 g_string_append_c(buf, c);
597 unescaped = g_string_free(buf, FALSE);
599 #endif
600 if (unescaped && !g_utf8_validate(unescaped, -1, (const gchar **)&tmp))
601 *tmp = '\0';
603 return unescaped;
606 GSList *sipe_utils_slist_insert_unique_sorted(GSList *list,
607 gpointer data,
608 GCompareFunc func,
609 GDestroyNotify destroy)
611 if (g_slist_find_custom(list, data, func)) {
612 /* duplicate */
613 if (destroy)
614 (*destroy)(data);
615 return(list);
616 } else {
617 /* unique: list takes ownership of "data" */
618 return(g_slist_insert_sorted(list, data, func));
622 void sipe_utils_slist_free_full(GSList *list,
623 GDestroyNotify free)
625 #if GLIB_CHECK_VERSION(2,28,0)
626 g_slist_free_full(list, free);
627 #else
628 GSList *entry = list;
629 while (entry) {
630 (*free)(entry->data);
631 entry = entry->next;
633 g_slist_free(list);
634 #endif
638 Local Variables:
639 mode: c
640 c-file-style: "bsd"
641 indent-tabs-mode: t
642 tab-width: 8
643 End: