1 /*
2 * utils.c -- Various utility functions
3 *
4 * Copyright (C) 2005-2014 Mikael Berthe <mikael@lilotux.net>
5 * Some of the ut_* functions are derived from Cabber debug/log code.
6 * from_iso8601() comes from the Pidgin (libpurple) project.
7 *
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 (at
11 * your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <config.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <errno.h>
29
30 #ifdef HAVE_LIBIDN
31 #include <idna.h>
32 #include <stringprep.h>
33 static char idnprep[1024];
34 #endif
35
36 #include <glib.h>
37 #include <glib/gprintf.h>
38
39 /* For Cygwin (thanks go to Yitzchak Scott-Thoennes) */
40 #ifdef __CYGWIN__
41 # define timezonevar
42 extern long timezone;
43 #endif
44 #include <time.h>
45 #include <unistd.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <ctype.h>
49
50 #include "utils.h"
51 #include "logprint.h"
52 #include "settings.h"
53 #include "main.h"
54 #include "screen.h"
55
56 static int DebugEnabled;
57 static char *FName;
58
59 // jidtodisp(jid)
60 // Strips the resource part from the jid
61 // The caller should g_free the result after use.
jidtodisp(const char * fjid)62 char *jidtodisp(const char *fjid)
63 {
64 char *ptr;
65 char *alias;
66
67 if (!fjid) {
68 scr_LogPrint(LPRINT_LOGNORM, "** jidtodisp: NULL JID, "
69 "this is probably a bug, please report!");
70 return NULL;
71 }
72
73 alias = g_strdup(fjid);
74
75 if ((ptr = strchr(alias, JID_RESOURCE_SEPARATOR)) != NULL) {
76 *ptr = 0;
77 }
78 return alias;
79 }
80
81 // The caller must free the string after use.
jid_get_username(const char * fjid)82 char *jid_get_username(const char *fjid)
83 {
84 char *ptr;
85 char *username;
86
87 username = g_strdup(fjid);
88 if ((ptr = strchr(username, JID_DOMAIN_SEPARATOR)) != NULL) {
89 *ptr = 0;
90 }
91 return username;
92 }
93
94 // The caller must free the string after use.
get_servername(const char * username,const char * servername)95 char *get_servername(const char *username, const char *servername)
96 {
97 char *ptr;
98 char *server;
99
100 if (!username) {
101 return NULL;
102 }
103 if ((ptr = strchr(username, JID_DOMAIN_SEPARATOR)) != NULL) {
104 server = g_strdup(ptr+1);
105 return server;
106 }
107
108 return g_strdup(servername);
109 }
110
111 // The caller must free the string after use.
compose_jid(const char * username,const char * servername,const char * resource)112 char *compose_jid(const char *username, const char *servername,
113 const char *resource)
114 {
115 char *fjid;
116
117 if (!strchr(username, JID_DOMAIN_SEPARATOR)) {
118 fjid = g_strdup_printf("%s%c%s%c%s", username,
119 JID_DOMAIN_SEPARATOR, servername,
120 JID_RESOURCE_SEPARATOR, resource);
121 } else {
122 fjid = g_strdup_printf("%s%c%s", username,
123 JID_RESOURCE_SEPARATOR, resource);
124 }
125 return fjid;
126 }
127
jid_equal(const char * jid1,const char * jid2)128 gboolean jid_equal(const char *jid1, const char *jid2)
129 {
130 char *a,*b;
131 int ret;
132 if (!jid1 && !jid2)
133 return TRUE;
134 if (!jid1 || !jid2)
135 return FALSE;
136
137 a = jidtodisp(jid1);
138 b = jidtodisp(jid2);
139 ret = strcasecmp(a, b);
140 g_free(a);
141 g_free(b);
142 return (ret == 0) ? TRUE : FALSE;
143 }
144
jid_get_resource_name(const char * fjid)145 const char *jid_get_resource_name(const char *fjid)
146 {
147 const char * resource_name = NULL;
148 if (fjid) {
149 resource_name = strchr(fjid, JID_RESOURCE_SEPARATOR);
150 if (resource_name)
151 resource_name++;
152 }
153 return resource_name;
154 }
155
156 // expand_filename(filename)
157 // Expand "~/" with the $HOME env. variable in a file name.
158 // The caller must free the string after use.
expand_filename(const char * fname)159 char *expand_filename(const char *fname)
160 {
161 if (!fname)
162 return NULL;
163 if (!strncmp(fname, "~/", 2)) {
164 char *homedir = getenv("HOME");
165 if (homedir)
166 return g_strdup_printf("%s%s", homedir, fname+1);
167 }
168 return g_strdup(fname);
169 }
170
171 #ifndef LOUDMOUTH_USES_SHA256
172 // fingerprint_to_hex(fprstr, hex, fpr_len)
173 // Convert the binary fingerprint fprstr (which is fpr_len bytes long)
174 // to a NULL-terminated hexadecimal string hex.
175 // The destination array hex should have been preallocated by the caller,
176 // and should be big enough (i.e. >= 3*fpr_len bytes).
fingerprint_to_hex(const char * fprstr,char * hex,size_t fpr_len)177 void fingerprint_to_hex(const char *fprstr, char *hex, size_t fpr_len)
178 {
179 unsigned int i;
180 const unsigned char *fpr = (const unsigned char *)fprstr;
181 char *p;
182
183 hex[0] = 0;
184 if (!fpr || fpr_len < 16) return;
185
186 for (p = hex, i = 0; i < fpr_len - 1; i++, p+=3)
187 g_snprintf(p, 4, "%02X:", fpr[i]);
188 g_snprintf(p, 3, "%02X", fpr[i]);
189 }
190
191 // hex_to_fingerprint(hex, fpr, fpr_len)
192 // Convert the hexadecimal fingerprint hex to a byte array fpr[].
193 // The fpr array should have been preallocated with a size >= fpr_len.
hex_to_fingerprint(const char * hex,char * fpr,size_t fpr_len)194 gboolean hex_to_fingerprint(const char *hex, char *fpr, size_t fpr_len)
195 {
196 unsigned int i;
197 const char *p;
198
199 if (fpr_len < 16) return FALSE;
200
201 fpr[0] = 0;
202
203 if (strlen(hex) != fpr_len*3 - 1)
204 return FALSE;
205
206 for (i = 0, p = hex; i < fpr_len && *p && *(p+1); i++, p += 3) {
207 // Check we have two hex digits followed by a colon (or end of string)
208 if (!isxdigit(*p) || !isxdigit(*(p+1)))
209 return FALSE;
210 if (*(p+2) && (*(p+2) != ':'))
211 return FALSE;
212 fpr[i] = (char)g_ascii_strtoull(p, NULL, 16);
213 }
214 return TRUE;
215 }
216 #endif
217
tracelog_create(void)218 static gboolean tracelog_create(void)
219 {
220 FILE *fp;
221 struct stat buf;
222 int err;
223 char *v;
224
225 fp = fopen(FName, "a");
226 if (!fp) {
227 scr_LogPrint(LPRINT_NORMAL, "ERROR: Cannot open tracelog file: %s",
228 strerror(errno));
229 return FALSE;
230 }
231
232 err = fstat(fileno(fp), &buf);
233 if (err || buf.st_uid != geteuid()) {
234 fclose(fp);
235 if (err)
236 scr_LogPrint(LPRINT_NORMAL, "ERROR: cannot stat the tracelog file: %s",
237 strerror(errno));
238 else
239 scr_LogPrint(LPRINT_NORMAL, "ERROR: tracelog file does not belong to you!");
240 return FALSE;
241 }
242
243 if (fchmod(fileno(fp), S_IRUSR|S_IWUSR)) {
244 scr_LogPrint(LPRINT_NORMAL, "WARNING: Cannot set tracelog file permissions: %s",
245 strerror(errno));
246 }
247
248 v = mcabber_version();
249 fprintf(fp, "New trace log started. MCabber version %s\n"
250 "----------------------\n", v);
251 g_free(v);
252 fclose(fp);
253 return TRUE;
254 }
255
256 // The caller must free the string after use.
tracelog_level_guard(const gchar * key,const gchar * new_value)257 static gchar *tracelog_level_guard(const gchar *key, const gchar *new_value)
258 {
259 int new_level = 0;
260 if (new_value)
261 new_level = atoi(new_value);
262 if (DebugEnabled < 1 && new_level > 0 && FName && !tracelog_create())
263 DebugEnabled = 0;
264 else
265 DebugEnabled = new_level;
266 return g_strdup(new_value);
267 }
268
269 // The caller must free the string after use.
tracelog_file_guard(const gchar * key,const gchar * new_value)270 static gchar *tracelog_file_guard(const gchar *key, const gchar *new_value)
271 {
272 gchar *new_fname = NULL;
273
274 if (new_value)
275 new_fname = expand_filename(new_value);
276
277 if (g_strcmp0(FName, new_fname)) {
278 g_free(FName);
279 FName = new_fname;
280 if (DebugEnabled > 0 && !tracelog_create()) {
281 g_free(FName);
282 FName = NULL;
283 }
284 } else
285 g_free(new_fname);
286
287 return g_strdup(new_value);
288 }
289
290 // ut_init_debug()
291 // Install option guards before initial config file parsing.
ut_init_debug(void)292 void ut_init_debug(void)
293 {
294 DebugEnabled = 0;
295 FName = NULL;
296 settings_set_guard("tracelog_level", tracelog_level_guard);
297 settings_set_guard("tracelog_file", tracelog_file_guard);
298 }
299
ut_write_log(unsigned int flag,const char * data)300 void ut_write_log(unsigned int flag, const char *data)
301 {
302 if (!DebugEnabled || !FName) return;
303
304 if (((DebugEnabled >= 2) && (flag & (LPRINT_LOG|LPRINT_DEBUG))) ||
305 ((DebugEnabled == 1) && (flag & LPRINT_LOG))) {
306 FILE *fp = fopen(FName, "a+");
307 if (!fp) {
308 scr_LogPrint(LPRINT_NORMAL, "ERROR: Cannot open tracelog file: %s.",
309 strerror(errno));
310 return;
311 }
312
313 // Check file permissions again (it could be a new file)
314 fchmod(fileno(fp), S_IRUSR|S_IWUSR);
315
316 if (fputs(data, fp) == EOF)
317 scr_LogPrint(LPRINT_NORMAL, "ERROR: Cannot write to tracelog file.");
318 fclose(fp);
319 }
320 }
321
322 // checkset_perm(name, setmode)
323 // Check the permissions of the "name" file/dir
324 // If setmode is true, correct the permissions if they are wrong
325 // Return values: -1 == bad file/dir, 0 == success, 1 == cannot correct
checkset_perm(const char * name,unsigned int setmode)326 int checkset_perm(const char *name, unsigned int setmode)
327 {
328 int fd;
329 struct stat buf;
330
331 if (!name) return -1;
332
333 #ifdef __CYGWIN__
334 // Permission checking isn't efficient on Cygwin
335 return 0;
336 #endif
337
338 fd = stat(name, &buf);
339 if (fd == -1) return -1;
340
341 if (buf.st_uid != geteuid()) {
342 scr_LogPrint(LPRINT_LOGNORM, "Wrong file owner [%s]", name);
343 return 1;
344 }
345
346 if (buf.st_mode & (S_IRGRP | S_IWGRP | S_IXGRP) ||
347 buf.st_mode & (S_IROTH | S_IWOTH | S_IXOTH)) {
348 if (setmode) {
349 mode_t newmode = 0;
350 scr_LogPrint(LPRINT_LOGNORM, "Bad permissions [%s]", name);
351 if (S_ISDIR(buf.st_mode))
352 newmode |= S_IXUSR;
353 newmode |= S_IRUSR | S_IWUSR;
354 if (chmod(name, newmode)) {
355 scr_LogPrint(LPRINT_LOGNORM, "WARNING: Failed to correct permissions!");
356 return 1;
357 }
358 scr_LogPrint(LPRINT_LOGNORM, "Permissions have been corrected");
359 } else {
360 scr_LogPrint(LPRINT_LOGNORM, "WARNING: Bad permissions [%s]", name);
361 return 1;
362 }
363 }
364
365 return 0;
366 }
367
ut_get_tmpdir(void)368 const char *ut_get_tmpdir(void)
369 {
370 static const char *tmpdir;
371 const char *tmpvars[] = { "MCABBERTMPDIR", "TMP", "TMPDIR", "TEMP" };
372 unsigned int i;
373
374 if (tmpdir)
375 return tmpdir;
376
377 for (i = 0; i < (sizeof(tmpvars) / sizeof(const char *)); i++) {
378 tmpdir = getenv(tmpvars[i]);
379 if (tmpdir && tmpdir[0] && tmpdir[0] == '/' && tmpdir[1]) {
380 // Looks ok.
381 return tmpdir;
382 }
383 }
384
385 // Default temporary directory
386 tmpdir = "/tmp";
387 return tmpdir;
388 }
389
390 // to_iso8601(dststr, timestamp)
391 // Convert timestamp to iso8601 format, and store it in dststr.
392 // NOTE: dststr should be at last 19 chars long.
393 // Return should be 0
to_iso8601(char * dststr,time_t timestamp)394 int to_iso8601(char *dststr, time_t timestamp)
395 {
396 struct tm *tm_time;
397 int ret;
398
399 tm_time = gmtime(×tamp);
400
401 ret = snprintf(dststr, 19, "%.4d%02d%02dT%02d:%02d:%02dZ",
402 (int)(1900+tm_time->tm_year), tm_time->tm_mon+1, tm_time->tm_mday,
403 tm_time->tm_hour, tm_time->tm_min, tm_time->tm_sec);
404
405 return ((ret == -1) ? -1 : 0);
406 }
407
408 // from_iso8601(timestamp, utc)
409 // This function came from the Pidgin project, gaim_str_to_time().
410 // (Actually date may not be pure iso-8601)
411 // Thanks, guys!
412 // ** Modified by somian 10 Apr 2006 with advice from ysth.
from_iso8601(const char * timestamp,int utc)413 time_t from_iso8601(const char *timestamp, int utc)
414 {
415 struct tm t;
416 time_t retval = 0;
417 char buf[32];
418 char *c;
419 int tzoff = 0;
420 int hms_succ = 0;
421 int tmpyear;
422
423 time(&retval);
424 localtime_r(&retval, &t);
425
426 /* Reset time to midnight (00:00:00) */
427 t.tm_hour = t.tm_min = t.tm_sec = 0;
428
429 snprintf(buf, sizeof(buf), "%s", timestamp);
430 c = buf;
431
432 /* 4 digit year */
433 if (!sscanf(c, "%04d", &tmpyear)) return 0;
434 t.tm_year = tmpyear;
435 c+=4;
436 if (*c == '-')
437 c++;
438
439 t.tm_year -= 1900;
440
441 /* 2 digit month */
442 if (!sscanf(c, "%02d", &t.tm_mon)) return 0;
443 c+=2;
444 if (*c == '-')
445 c++;
446
447 t.tm_mon -= 1;
448
449 /* 2 digit day */
450 if (!sscanf(c, "%02d", &t.tm_mday)) return 0;
451 c+=2;
452 if (*c == 'T' || *c == '.') { /* we have more than a date, keep going */
453 c++; /* skip the "T" */
454
455 /* 2 digit hour */
456 if (sscanf(c, "%02d:%02d:%02d", &t.tm_hour, &t.tm_min, &t.tm_sec) == 3)
457 {
458 hms_succ = 1;
459 c += 8;
460 }
461 else if (sscanf(c, "%02d%02d%02d", &t.tm_hour, &t.tm_min, &t.tm_sec) == 3)
462 {
463 hms_succ = 1;
464 c += 6;
465 }
466
467 if (hms_succ) {
468 int tzhrs, tzmins;
469
470 if (*c == '.') /* dealing with precision we don't care about */
471 while (isdigit(*++c))
472 ;
473
474 if ((*c == '+' || *c == '-') &&
475 sscanf(c+1, "%02d:%02d", &tzhrs, &tzmins)) {
476 tzoff = tzhrs*60*60 + tzmins*60;
477 if (*c == '+')
478 tzoff *= -1;
479 }
480
481 if (tzoff || utc) {
482 #ifdef HAVE_TM_GMTOFF
483 tzoff += t.tm_gmtoff;
484 #else
485 # ifdef HAVE_TIMEZONE
486 tzset(); /* making sure */
487 tzoff -= timezone;
488 # endif
489 #endif
490 }
491 }
492 }
493
494 t.tm_isdst = -1;
495
496 retval = mktime(&t);
497
498 retval += tzoff;
499
500 return retval;
501 }
502
503 /**
504 * Derived from libjabber/jid.c, because the libjabber version is not
505 * really convenient for our usage.
506 *
507 * Check if the full JID is valid
508 * Return 0 if it is valid, non zero otherwise
509 */
check_jid_syntax(const char * fjid)510 int check_jid_syntax(const char *fjid)
511 {
512 const char *str;
513 const char *domain, *resource;
514 int domlen;
515 #ifdef HAVE_LIBIDN
516 char *idnpp;
517 int r;
518 #endif
519
520 if (!fjid) return 1;
521
522 domain = strchr(fjid, JID_DOMAIN_SEPARATOR);
523
524 /* the username is optional */
525 if (!domain) {
526 domain = fjid;
527 } else {
528 /* node identifiers may not be longer than 1023 bytes */
529 if ((domain == fjid) || (domain-fjid > 1023))
530 return 1;
531 domain++;
532
533 #ifdef HAVE_LIBIDN
534 idnpp = idnprep;
535 str = fjid;
536 while (*str != JID_DOMAIN_SEPARATOR)
537 *idnpp++ = *str++;
538 *idnpp = 0;
539
540 r = stringprep(idnprep, 1023, 0, stringprep_xmpp_nodeprep);
541 if (r != STRINGPREP_OK || !idnprep[0])
542 return 1;
543 /* the username looks okay */
544 #else
545 /* check for low and invalid ascii characters in the username */
546 for (str = fjid; *str != JID_DOMAIN_SEPARATOR; str++) {
547 if (*str <= ' ' || *str == ':' || *str == JID_DOMAIN_SEPARATOR ||
548 *str == '<' || *str == '>' || *str == '\'' ||
549 *str == '"' || *str == '&') {
550 return 1;
551 }
552 }
553 /* the username is okay as far as we can tell without LIBIDN */
554 #endif
555 }
556
557 resource = strchr(domain, JID_RESOURCE_SEPARATOR);
558
559 /* the resource is optional */
560 if (resource) {
561 domlen = resource - domain;
562 resource++;
563 /* resources may not be longer than 1023 bytes */
564 if ((*resource == '\0') || strlen(resource) > 1023)
565 return 1;
566 #ifdef HAVE_LIBIDN
567 strncpy(idnprep, resource, sizeof(idnprep));
568 r = stringprep(idnprep, 1023, 0, stringprep_xmpp_resourceprep);
569 if (r != STRINGPREP_OK || !idnprep[0])
570 return 1;
571 #endif
572 } else {
573 domlen = strlen(domain);
574 }
575
576 /* there must be a domain identifier */
577 if (domlen == 0) return 1;
578
579 /* and it must not be longer than 1023 bytes */
580 if (domlen > 1023) return 1;
581
582 /* /.+/ is not a valid domain name pattern */
583 for (str = domain; *str && *str != JID_RESOURCE_SEPARATOR; str++)
584 if (*str != '.') break;
585 if (!*str || *str == JID_RESOURCE_SEPARATOR)
586 return 1; /* domain contains only dots */
587
588 #ifdef HAVE_LIBIDN
589 idnpp = idnprep;
590 str = domain;
591 while (*str != '\0' && *str != JID_RESOURCE_SEPARATOR)
592 *idnpp++ = *str++;
593 *idnpp = 0;
594
595 r = stringprep_nameprep(idnprep, 1023);
596 if (r != STRINGPREP_OK || !idnprep[0])
597 return 1;
598
599 if (idna_to_ascii_8z(idnprep, &idnpp, IDNA_USE_STD3_ASCII_RULES) !=
600 IDNA_SUCCESS)
601 return 1;
602 else
603 free(idnpp);
604 #else
605 /* make sure the hostname is valid characters */
606 for (str = domain; *str != '\0' && *str != JID_RESOURCE_SEPARATOR; str++) {
607 if (!(isalnum(*str) || *str == '.' || *str == '-' || *str == '_'))
608 return 1;
609 }
610 #endif
611
612 /* it's okay as far as we can tell */
613 return 0;
614 }
615
616
mc_strtolower(char * str)617 void mc_strtolower(char *str)
618 {
619 if (!str) return;
620 for ( ; *str; str++)
621 *str = tolower(*str);
622 }
623
624 // strip_arg_special_chars(string)
625 // Remove quotes and backslashes before an escaped quote
626 // Only quotes need a backslash
627 // Ex.: ["a b"] -> [a b]; [a\"b] -> [a"b]
strip_arg_special_chars(char * s)628 void strip_arg_special_chars(char *s)
629 {
630 int instring = FALSE;
631 int escape = FALSE;
632 char *p, *t;
633
634 if (!s) return;
635
636 for (p = s; *p; p++) {
637 if (*p == '"') {
638 if (!escape) {
639 instring = !instring;
640 //memmove(p, p+1, strlen(p));
641 for (t=p; *t; t++)
642 *t = *(t+1);
643 p--;
644 } else
645 escape = FALSE;
646 } else if (*p == '\\') {
647 if (!escape) {
648 //memmove(p, p+1, strlen(p));
649 for (t=p; *t; t++)
650 *t = *(t+1);
651 p--;
652 }
653 escape = !escape;
654 } else
655 escape = FALSE;
656 }
657 }
658
659 // split_arg(arg, n, preservelast)
660 // Split the string arg into a maximum of n pieces, taking care of
661 // double quotes.
662 // Return a null-terminated array of strings. This array should be freed
663 // by the caller after use, for example with free_arg_lst().
664 // If dontstriplast is true, the Nth argument isn't stripped (i.e. no
665 // processing of quote chars)
split_arg(const char * arg,unsigned int n,int dontstriplast)666 char **split_arg(const char *arg, unsigned int n, int dontstriplast)
667 {
668 char **arglst;
669 const char *p, *start, *end;
670 unsigned int i = 0;
671 int instring = FALSE;
672 int escape = FALSE;
673
674 arglst = g_new0(char*, n+1);
675
676 if (!arg || !n) return arglst;
677
678 // Skip leading space
679 for (start = arg; *start && *start == ' '; start++) ;
680 // End of string pointer
681 for (end = start; *end; end++) ;
682 // Skip trailing space
683 while (end > start+1 && *(end-1) == ' ')
684 end--;
685
686 for (p = start; p < end; p++) {
687 if (*p == '"' && !escape)
688 instring = !instring;
689 if (*p == '\\' && !escape)
690 escape = TRUE;
691 else if (escape)
692 escape = FALSE;
693 if (*p == ' ' && !instring && i+1 < n) {
694 // end of parameter
695 *(arglst+i) = g_strndup(start, p-start);
696 strip_arg_special_chars(*(arglst+i));
697 for (start = p+1; *start && *start == ' '; start++) ;
698 p = start-1;
699 i++;
700 }
701 }
702
703 if (start < end) {
704 *(arglst+i) = g_strndup(start, end-start);
705 if (!dontstriplast || i+1 < n)
706 strip_arg_special_chars(*(arglst+i));
707 }
708
709 return arglst;
710 }
711
712 // free_arg_lst(arglst)
713 // Free an array allocated by split_arg()
free_arg_lst(char ** arglst)714 void free_arg_lst(char **arglst)
715 {
716 char **arg_elt;
717
718 for (arg_elt = arglst; *arg_elt; arg_elt++)
719 g_free(*arg_elt);
720 g_free(arglst);
721 }
722
723 // replace_nl_with_dots(bufstr)
724 // Replace '\n' with "(...)" (or with a NUL if the string is too short)
replace_nl_with_dots(char * bufstr)725 void replace_nl_with_dots(char *bufstr)
726 {
727 char *p = strchr(bufstr, '\n');
728 if (p) {
729 if (strlen(p) >= 5)
730 strcpy(p, "(...)");
731 else
732 *p = 0;
733 }
734 }
735
736 // ut_expand_tabs(text)
737 // Expand tabs and filter out some bad chars in string text.
738 // If there is no tab and no bad chars in the string, a pointer to text
739 // is returned (be careful _not_ to free the pointer in this case).
740 // If there are some tabs or bad chars, a new string with expanded chars
741 // and no bad chars is returned; this is up to the caller to free this
742 // string after use.
ut_expand_tabs(const char * text)743 char *ut_expand_tabs(const char *text)
744 {
745 char *xtext, *linestart;
746 char *p, *q;
747 guint n = 0, bc = 0;
748
749 if (!text)
750 return NULL;
751
752 xtext = (char*)text;
753 for (p=xtext; *p; p++)
754 if (*p == '\t')
755 n++;
756 else if (*p == '\x0d')
757 bc++;
758 // XXX Are there other special chars we should filter out?
759
760 if (!n && !bc)
761 return (char*)text;
762
763 xtext = g_new(char, strlen(text) + 1 + 8*n);
764 p = (char*)text;
765 q = linestart = xtext;
766 do {
767 if (*p == '\t') {
768 do { *q++ = ' '; } while ((q-linestart)%8);
769 } else if (*p != '\x0d') {
770 *q++ = *p;
771 if (*p =='\n')
772 linestart = q;
773 }
774 } while (*p++);
775
776 return xtext;
777 }
778
779 // ut_unescape_tabs_cr(text)
780 // Expand CR or TAB character sequences (\n, \t) in string text.
781 // If there is no CR/TAB in text, then the original pointer is returned
782 // (be careful _not_ to free the pointer in this case).
783 // If there are some unescaped sequences, a new string with those chars
784 // replaced with real newline/tab characters is allocated; in this case
785 // this is up to the caller to free this string after use.
ut_unescape_tabs_cr(const char * text)786 char *ut_unescape_tabs_cr(const char *text)
787 {
788 char *xtext, *linestart;
789 char *p, *q;
790
791 if (!text)
792 return NULL;
793
794 p = g_strstr_len(text, -1, "\\n");
795 if (!p) {
796 p = g_strstr_len(text, -1, "\\t");
797 if (!p)
798 return (char*)text;
799 }
800
801 xtext = g_new(char, strlen(text) + 1);
802 p = (char*)text;
803 q = linestart = xtext;
804 do {
805 if (*p == '\\') {
806 if (*(p+1) == '\\' && (*(p+2) == 'n' || *(p+2) == 't')) {
807 // This is an escaped CR sequence
808 *q++ = '\\';
809 *q++ = 'n';
810 p += 2;
811 continue;
812 }
813 if (*(p+1) == 'n' || *(p+1) == 't') {
814 // This is a CR sequence
815 p++;
816 *q++ = (*p == 'n' ? '\n' : '\t');
817 continue;
818 }
819 }
820 *q++ = *p;
821 } while (*p++);
822
823 return xtext;
824 }
825
826
827 /* Cygwin's newlib does not have strcasestr() */
828 /* The author of the code before the endif is
829 * Jeffrey Stedfast <fejj@ximian.com>
830 * and this code is reusable in compliance with the GPL v2. -- somian */
831
832 #if !defined(HAVE_STRCASESTR)
833
834 # define lowercase(c) (isupper ((int) (c)) ? tolower ((int) (c)) : (int) (c))
835 # define bm_index(c, icase) ((icase) ? lowercase (c) : (int) (c))
836 # define bm_equal(c1, c2, icase) ((icase) ? lowercase (c1) == lowercase (c2) : (c1) == (c2))
837
838 /* FIXME: this is just a guess... should really do some performace tests to get an accurate measure */
839 # define bm_optimal(hlen, nlen) (((hlen) ? (hlen) > 20 : 1) && (nlen) > 10 ? 1 : 0)
840
841 static unsigned char *
__boyer_moore(const unsigned char * haystack,size_t haystacklen,const unsigned char * needle,size_t needlelen,int icase)842 __boyer_moore (const unsigned char *haystack, size_t haystacklen,
843 const unsigned char *needle, size_t needlelen, int icase)
844 {
845 register unsigned char *hc_ptr, *nc_ptr;
846 unsigned char *he_ptr, *ne_ptr, *h_ptr;
847 size_t skiptable[256], n;
848 register int i;
849
850 #ifdef BOYER_MOORE_CHECKS
851 /* we don't need to do these checks since memmem/strstr/etc do it already */
852 /* if the haystack is shorter than the needle then we can't possibly match */
853 if (haystacklen < needlelen)
854 return NULL;
855
856 /* instant match if the pattern buffer is 0-length */
857 if (needlelen == 0)
858 return (unsigned char *) haystack;
859 #endif /* BOYER_MOORE_CHECKS */
860
861 /* set a pointer at the end of each string */
862 ne_ptr = (unsigned char *) needle + needlelen - 1;
863 he_ptr = (unsigned char *) haystack + haystacklen - 1;
864
865 /* create our skip table */
866 for (i = 0; i < 256; i++)
867 skiptable[i] = needlelen;
868 for (nc_ptr = (unsigned char *) needle; nc_ptr < ne_ptr; nc_ptr++)
869 skiptable[bm_index (*nc_ptr, icase)] = (size_t) (ne_ptr - nc_ptr);
870
871 h_ptr = (unsigned char *) haystack;
872 while (haystacklen >= needlelen) {
873 hc_ptr = h_ptr + needlelen - 1; /* set the haystack compare pointer */
874 nc_ptr = ne_ptr; /* set the needle compare pointer */
875
876 /* work our way backwards till they don't match */
877 for (i = 0; nc_ptr > (unsigned char *) needle; nc_ptr--, hc_ptr--, i++)
878 if (!bm_equal (*nc_ptr, *hc_ptr, icase))
879 break;
880
881 if (!bm_equal (*nc_ptr, *hc_ptr, icase)) {
882 n = skiptable[bm_index (*hc_ptr, icase)];
883 if (n == needlelen && i)
884 if (bm_equal (*ne_ptr, ((unsigned char *) needle)[0], icase))
885 n--;
886 h_ptr += n;
887 haystacklen -= n;
888 } else
889 return (unsigned char *) h_ptr;
890 }
891
892 return NULL;
893 }
894
895 /*
896 * strcasestr:
897 * @haystack: string to search
898 * @needle: substring to search for
899 *
900 * Finds the first occurence of the substring @needle within the
901 * string @haystack ignoring case.
902 *
903 * Returns a pointer to the beginning of the substring match within
904 * @haystack, or NULL if the substring is not found.
905 **/
906 char *
strcasestr(const char * haystack,const char * needle)907 strcasestr (const char *haystack, const char *needle)
908 {
909 register unsigned char *h, *n, *hc, *nc;
910 size_t needlelen;
911
912 needlelen = strlen (needle);
913
914 if (needlelen == 0) {
915 return (char *) haystack;
916 } else if (bm_optimal (0, needlelen)) {
917 return (char *) __boyer_moore ((const unsigned char *) haystack,
918 strlen (haystack),
919 (const unsigned char *) needle,
920 needlelen, 1);
921 }
922
923 h = (unsigned char *) haystack;
924 n = (unsigned char *) needle;
925
926 while (*(h + needlelen - 1)) {
927 if (lowercase (*h) == lowercase (*n)) {
928 for (hc = h + 1, nc = n + 1; *hc && *nc; hc++, nc++)
929 if (lowercase (*hc) != lowercase (*nc))
930 break;
931
932 if (!*nc)
933 return (char *) h;
934 }
935 h++;
936 }
937 return NULL;
938 }
939 #endif /* !HAVE_STRCASESTR */
940
941 // startswith(str, word, ignore_case)
942 // Returns TRUE if string str starts with word.
startswith(const char * str,const char * word,guint ignore_case)943 int startswith(const char *str, const char *word, guint ignore_case)
944 {
945 if (ignore_case && !strncasecmp(str, word, strlen(word)))
946 return TRUE;
947 else if (!ignore_case && !strncmp(str, word, strlen(word)))
948 return TRUE;
949 return FALSE;
950 }
951
952 // mkcmdstr(cmd) returns a pointer to a const string with the command
953 // prefixed with COMMAND_CHAR.
mkcmdstr(const char * cmd)954 const char *mkcmdstr(const char *cmd)
955 {
956 static char fcmd[INPUTLINE_LENGTH+1];
957
958 fcmd[0] = COMMAND_CHAR;
959 fcmd[1] = 0;
960
961 strncat(fcmd+1, cmd, INPUTLINE_LENGTH-1);
962 return fcmd;
963 }
964
965 /* vim: set et cindent cinoptions=>2\:2(0 ts=2 sw=2: For Vim users... */
966