coverity: fix STACK_USE warning
[siplcs.git] / src / core / sipe-utils.c
blobedee25783b322f530ba584fed5e756f75b914ad8
1 /**
2 * @file sipe-utils.c
4 * pidgin-sipe
6 * Copyright (C) 2009-2010 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 #ifdef _WIN32
32 /* for network */
33 #include "win32/libc_interface.h"
34 #include <nspapi.h>
35 #else
36 #if defined(__APPLE__) || defined(__FreeBSD__)
37 #include <sys/socket.h>
38 #endif
39 #include <unistd.h>
40 #include <net/if.h>
41 #include <sys/types.h>
42 #include <sys/ioctl.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #endif
47 #include "sipe-backend.h"
48 #include "sipe-core.h" /* to ensure same API for backends */
49 #include "sipe-core-private.h"
50 #include "sipe-utils.h"
51 #include "uuid.h"
52 #include "sipe.h"
54 /* Generate 32 random bits */
55 #define RANDOM32BITS (rand() & 0xFFFF)
57 gchar *gencallid(void)
59 return g_strdup_printf("%04Xg%04Xa%04Xi%04Xm%04Xt%04Xb%04Xx%04Xx",
60 RANDOM32BITS, RANDOM32BITS, RANDOM32BITS,
61 RANDOM32BITS, RANDOM32BITS, RANDOM32BITS,
62 RANDOM32BITS, RANDOM32BITS);
65 gchar *gentag(void)
67 return g_strdup_printf("%04d%04d", RANDOM32BITS, RANDOM32BITS);
70 gchar *genconfid(void)
72 return g_strdup_printf("%04X%04X%04X%04X%04X%04X%04X%04X",
73 RANDOM32BITS, RANDOM32BITS, RANDOM32BITS,
74 RANDOM32BITS, RANDOM32BITS, RANDOM32BITS,
75 RANDOM32BITS, RANDOM32BITS);
78 gchar *get_contact(const struct sipe_core_private *sipe_private)
80 return g_strdup(sipe_private->contact);
83 gchar *parse_from(const gchar *hdr)
85 gchar *from;
86 const gchar *tmp, *tmp2 = hdr;
88 if (!hdr) return NULL;
89 SIPE_DEBUG_INFO("parsing address out of %s", hdr);
90 tmp = strchr(hdr, '<');
92 /* i hate the different SIP UA behaviours... */
93 if (tmp) { /* sip address in <...> */
94 tmp2 = tmp + 1;
95 tmp = strchr(tmp2, '>');
96 if (tmp) {
97 from = g_strndup(tmp2, tmp - tmp2);
98 } else {
99 SIPE_DEBUG_INFO_NOFORMAT("found < without > in From");
100 return NULL;
102 } else {
103 tmp = strchr(tmp2, ';');
104 if (tmp) {
105 from = g_strndup(tmp2, tmp - tmp2);
106 } else {
107 from = g_strdup(tmp2);
110 SIPE_DEBUG_INFO("got %s", from);
111 return from;
114 int parse_cseq(const gchar *hdr)
116 int res = -1;
117 gchar **items;
118 items = g_strsplit(hdr, " ", 1);
119 if (items[0]) {
120 res = atoi(items[0]);
122 g_strfreev(items);
123 return res;
126 gchar *sip_uri_from_name(const gchar *name)
128 return(g_strdup_printf("sip:%s", name));
131 gchar *sip_uri(const gchar *string)
133 return(strstr(string, "sip:") ? g_strdup(string) : sip_uri_from_name(string));
136 gchar *
137 get_epid(struct sipe_core_private *sipe_private)
139 if (!sipe_private->epid) {
140 gchar *self_sip_uri = sip_uri_self(sipe_private);
141 sipe_private->epid = sipe_get_epid(self_sip_uri,
142 g_get_host_name(),
143 sipe_backend_network_ip_address());
144 g_free(self_sip_uri);
146 return g_strdup(sipe_private->epid);
149 guint
150 sipe_get_pub_instance(struct sipe_core_private *sipe_private,
151 int publication_key)
153 unsigned res = 0;
154 gchar *epid = get_epid(sipe_private);
156 sscanf(epid, "%08x", &res);
157 g_free(epid);
159 if (publication_key == SIPE_PUB_DEVICE) {
160 /* as is */
161 } else if (publication_key == SIPE_PUB_STATE_MACHINE) { /* First hexadecimal digit is 0x3 */
162 res = (res >> 4) | 0x30000000;
163 } else if (publication_key == SIPE_PUB_STATE_USER) {
164 res = 0x20000000; /* fixed */
165 } else if (publication_key == SIPE_PUB_STATE_CALENDAR) { /* First hexadecimal digit is 0x4 */
166 res = (res >> 4) | 0x40000000;
167 } else if (publication_key == SIPE_PUB_STATE_CALENDAR_OOF) { /* First hexadecimal digit is 0x5 */
168 res = (res >> 4) | 0x50000000;
169 } else if (publication_key == SIPE_PUB_CALENDAR_DATA ||
170 publication_key == SIPE_PUB_NOTE_OOF)
171 { /* First hexadecimal digit is 0x4 */
172 unsigned calendar_id = 0;
173 char *mail_hash = sipe_get_epid(SIPE_ACCOUNT_DATA_PRIVATE->email, "", "");
175 sscanf(mail_hash, "%08x", &calendar_id);
176 g_free(mail_hash);
177 res = (calendar_id >> 4) | 0x40000000;
180 return res;
183 gboolean
184 sipe_is_bad_alias(const char *uri,
185 const char *alias)
187 char *uri_alias;
188 gboolean result = FALSE;
190 if (!uri) return FALSE;
191 if (!alias) return TRUE;
193 if (g_str_has_prefix(alias, "sip:") || g_str_has_prefix(alias, "sips:")) return TRUE;
195 /* check if alias is just SIP URI but without 'sip:' prefix */
196 uri_alias = sip_uri_from_name(alias);
197 if (sipe_strcase_equal(uri, uri_alias)) {
198 result = TRUE;
200 g_free(uri_alias);
202 return result;
205 gboolean
206 is_empty(const char *st)
208 if (!st || strlen(st) == 0)
210 return TRUE;
212 /* suspecious leading or trailing staces */
213 else if (isspace((unsigned char) *st) ||
214 isspace((unsigned char) *(st + strlen(st) - 1)))
216 /* to not modify original string */
217 char *dup = g_strdup(st);
218 if (strlen(g_strstrip(dup)) == 0) {
219 g_free(dup);
220 return TRUE;
222 g_free(dup);
224 return FALSE;
227 /** Returns newly allocated string. Must be g_free()'d */
228 char *
229 replace(const char *st,
230 const char *search,
231 const char *replace)
233 char **tmp;
234 char *res;
236 if (!st) return NULL;
238 res = g_strjoinv(replace, tmp = g_strsplit(st, search, -1));
239 g_strfreev(tmp);
240 return res;
243 void sipe_utils_message_debug(const gchar *type,
244 const gchar *header,
245 const gchar *body,
246 gboolean sending)
248 if (sipe_backend_debug_enabled()) {
249 GString *str = g_string_new("");
250 GTimeVal currtime;
251 gchar *time_str;
252 const char *marker = sending ?
253 ">>>>>>>>>>" :
254 "<<<<<<<<<<";
255 gchar *tmp;
257 g_get_current_time(&currtime);
258 time_str = g_time_val_to_iso8601(&currtime);
259 g_string_append_printf(str, "\nMESSAGE START %s %s - %s\n", marker, type, time_str);
260 g_string_append(str, tmp = replace(header, "\r\n", "\n"));
261 g_free(tmp);
262 g_string_append(str, "\n");
263 if (body) {
264 g_string_append(str, tmp = replace(body, "\r\n", "\n"));
265 g_free(tmp);
266 g_string_append(str, "\n");
268 g_string_append_printf(str, "MESSAGE END %s %s - %s", marker, type, time_str);
269 g_free(time_str);
270 SIPE_DEBUG_INFO_NOFORMAT(str->str);
271 g_string_free(str, TRUE);
275 gboolean
276 sipe_strequal(const gchar *left, const gchar *right)
278 #if GLIB_CHECK_VERSION(2,16,0)
279 return (g_strcmp0(left, right) == 0);
280 #else
281 return ((left == NULL && right == NULL) ||
282 (left != NULL && right != NULL && strcmp(left, right) == 0));
283 #endif
286 gboolean
287 sipe_strcase_equal(const gchar *left, const gchar *right)
289 return ((left == NULL && right == NULL) ||
290 (left != NULL && right != NULL && g_ascii_strcasecmp(left, right) == 0));
293 gint sipe_strcompare(gconstpointer a, gconstpointer b)
295 #if GLIB_CHECK_VERSION(2,16,0)
296 return (g_strcmp0(a, b));
297 #else
298 if (!a)
299 return -(a != b);
300 if (!b)
301 return a != b;
302 return strcmp(a, b);
303 #endif
306 time_t
307 sipe_utils_str_to_time(const gchar *timestamp)
309 GTimeVal time;
310 guint len;
312 /* We have to make sure that the ISO8601 contains a time zone offset,
313 otherwise the time is interpreted as local time, not UTC!
314 @TODO: is there a better way to check this? */
315 if (timestamp && (len = strlen(timestamp) > 0) &&
316 isdigit(timestamp[len - 1])) {
317 gchar *tmp = g_strdup_printf("%sZ", timestamp);
318 g_time_val_from_iso8601(tmp, &time);
319 g_free(tmp);
320 } else {
321 g_time_val_from_iso8601(timestamp, &time);
323 return time.tv_sec;
326 gchar *
327 sipe_utils_time_to_str(time_t timestamp)
329 GTimeVal time = { timestamp, 0 };
330 return g_time_val_to_iso8601(&time);
333 size_t
334 hex_str_to_buff(const char *hex_str, guint8 **buff)
336 char two_digits[3];
337 size_t length;
338 size_t i;
340 if (!buff) return 0;
341 if (!hex_str) return 0;
343 length = strlen(hex_str)/2;
344 *buff = (unsigned char *)g_malloc(length);
345 for (i = 0; i < length; i++) {
346 two_digits[0] = hex_str[i * 2];
347 two_digits[1] = hex_str[i * 2 + 1];
348 two_digits[2] = '\0';
349 (*buff)[i] = (unsigned char)strtoul(two_digits, NULL, 16);
352 return length;
355 char *
356 buff_to_hex_str(const guint8 *buff, const size_t buff_len)
358 char *res;
359 size_t i, j;
361 if (!buff) return NULL;
363 res = g_malloc(buff_len * 2 + 1);
364 for (i = 0, j = 0; i < buff_len; i++, j+=2) {
365 sprintf(&res[j], "%02X", buff[i]);
367 res[j] = '\0';
368 return res;
371 gboolean
372 sipe_utils_parse_lines(GSList **list, gchar **lines, gchar *delimiter)
374 int i;
375 gchar **parts;
376 gchar *dummy;
377 gchar *dummy2;
378 gchar *tmp;
380 for(i = 0; lines[i] && strlen(lines[i]) > 2; i++) {
381 parts = g_strsplit(lines[i], delimiter, 2);
382 if(!parts[0] || !parts[1]) {
383 g_strfreev(parts);
384 return FALSE;
386 dummy = parts[1];
387 dummy2 = 0;
388 while(*dummy==' ' || *dummy=='\t') dummy++;
389 dummy2 = g_strdup(dummy);
390 while(lines[i+1] && (lines[i+1][0]==' ' || lines[i+1][0]=='\t')) {
391 i++;
392 dummy = lines[i];
393 while(*dummy==' ' || *dummy=='\t') dummy++;
394 tmp = g_strdup_printf("%s %s",dummy2, dummy);
395 g_free(dummy2);
396 dummy2 = tmp;
398 *list = sipe_utils_nameval_add(*list, parts[0], dummy2);
399 g_free(dummy2);
400 g_strfreev(parts);
403 return TRUE;
406 GSList*
407 sipe_utils_nameval_add(GSList* list, const gchar *name, const gchar *value)
409 struct sipnameval *element = g_new0(struct sipnameval,1);
411 /* SANITY CHECK: the calling code must be fixed if this happens! */
412 if (!value) {
413 SIPE_DEBUG_ERROR("sipe_utils_nameval_add: NULL value for %s",
414 name);
415 value = "";
418 element->name = g_strdup(name);
419 element->value = g_strdup(value);
420 return g_slist_append(list, element);
423 void
424 sipe_utils_nameval_free(GSList *list) {
425 struct sipnameval *elem;
426 while(list) {
427 elem = list->data;
428 list = g_slist_remove(list,elem);
429 g_free(elem->name);
430 g_free(elem->value);
431 g_free(elem);
435 const gchar *
436 sipe_utils_nameval_find(const GSList *list, const gchar *name)
438 return sipe_utils_nameval_find_instance (list, name, 0);
441 const gchar *
442 sipe_utils_nameval_find_instance(const GSList *list, const gchar *name, int which)
444 const GSList *tmp;
445 struct sipnameval *elem;
446 int i = 0;
447 tmp = list;
448 while(tmp) {
449 elem = tmp->data;
450 // OCS2005 can send the same header in either all caps or mixed case
451 if (sipe_strcase_equal(elem->name, name)) {
452 if (i == which) {
453 return elem->value;
455 i++;
457 tmp = g_slist_next(tmp);
459 return NULL;
462 gchar *sipe_utils_str_replace(const gchar *string,
463 const gchar *delimiter,
464 const gchar *replacement)
466 gchar **split;
467 gchar *result;
469 if (!string || !delimiter || !replacement) return NULL;
471 split = g_strsplit(string, delimiter, 0);
472 result = g_strjoinv(replacement, split);
473 g_strfreev(split);
475 return result;
478 void sipe_utils_shrink_buffer(struct sipe_transport_connection *conn,
479 const gchar *unread)
481 conn->buffer_used -= unread - conn->buffer;
482 /* string terminator is not included in buffer_used */
483 memmove(conn->buffer, unread, conn->buffer_used + 1);
487 * Calling sizeof(struct ifreq) isn't always correct on
488 * Mac OS X (and maybe others).
490 #ifdef _SIZEOF_ADDR_IFREQ
491 # define HX_SIZE_OF_IFREQ(a) _SIZEOF_ADDR_IFREQ(a)
492 #else
493 # define HX_SIZE_OF_IFREQ(a) sizeof(a)
494 #endif
496 #define IFREQ_MAX 32
498 const char * sipe_utils_get_suitable_local_ip(int fd)
500 int source = (fd >= 0) ? fd : socket(PF_INET,SOCK_STREAM, 0);
502 if (source >= 0) {
503 struct ifreq *buffer = g_new0(struct ifreq, IFREQ_MAX);
504 struct ifconf ifc;
505 guint32 lhost = htonl(127 * 256 * 256 * 256 + 1);
506 guint32 llocal = htonl((169 << 24) + (254 << 16));
507 guint i;
508 static char ip[16];
510 ifc.ifc_len = sizeof(struct ifreq) * IFREQ_MAX;
511 ifc.ifc_req = buffer;
512 ioctl(source, SIOCGIFCONF, &ifc);
514 if (fd < 0)
515 close(source);
517 for (i = 0; i < IFREQ_MAX; i++)
519 struct ifreq *ifr = &buffer[i];
521 if (ifr->ifr_addr.sa_family == AF_INET)
523 struct sockaddr_in sin;
524 memcpy(&sin, &ifr->ifr_addr, sizeof(struct sockaddr_in));
525 if (sin.sin_addr.s_addr != lhost
526 && (sin.sin_addr.s_addr & htonl(0xFFFF0000)) != llocal)
528 long unsigned int add = ntohl(sin.sin_addr.s_addr);
529 g_snprintf(ip, 16, "%lu.%lu.%lu.%lu",
530 ((add >> 24) & 255),
531 ((add >> 16) & 255),
532 ((add >> 8) & 255),
533 add & 255);
535 g_free(buffer);
536 return ip;
540 g_free(buffer);
543 return "0.0.0.0";
546 gchar *sipe_utils_presence_key(const gchar *uri)
548 return g_strdup_printf("<presence><%s>", uri);
551 gchar *sipe_utils_subscription_key(const gchar *event,
552 const gchar *uri)
554 gchar *key = NULL;
556 if (!is_empty(event)) {
557 if (!g_ascii_strcasecmp(event, "presence")) {
558 /* Subscription is identified by <presence><uri> key */
559 key = sipe_utils_presence_key(uri);
560 } else {
561 /* Subscription is identified by <event> key */
562 key = g_strdup_printf("<%s>", event);
566 return key;
570 Local Variables:
571 mode: c
572 c-file-style: "bsd"
573 indent-tabs-mode: t
574 tab-width: 8
575 End: