source: util.c @ a359456

release-1.7
Last change on this file since a359456 was a359456, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Fixup owl_util_recursive_resolve_link to handle relative symlinks Relative paths in symlinks are resolve relative to the parent directory. We need to correctly handle this case.
  • Property mode set to 100644
File size: 18.9 KB
Line 
1#include "owl.h"
2#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5#include <ctype.h>
6#include <pwd.h>
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <assert.h>
10#include <glib.h>
11#include <glib/gstdio.h>
12#include <glib-object.h>
13
14char **atokenize(const char *buffer, const char *sep, int *i)
15{
16  /* each element of return must be freed by user */
17  char **args;
18  char *workbuff, *foo;
19  int done=0, first=1, count=0;
20
21  workbuff = owl_strdup(buffer);
22
23  args=NULL;
24  while (!done) {
25    if (first) {
26      first=0;
27      foo=strtok(workbuff, sep);
28    } else {
29      foo=strtok(NULL, sep);
30    }
31    if (foo==NULL) {
32      done=1;
33    } else {
34      args=owl_realloc(args, sizeof(char *) * (count+1));
35      args[count] = owl_strdup(foo);
36      count++;
37    }
38  }
39  *i=count;
40  owl_free(workbuff);
41  return(args);
42}
43
44const char *skiptokens(const char *buff, int n) {
45  /* skips n tokens and returns where that would be. */
46  char quote = 0;
47  while (*buff && n>0) {
48      while (*buff == ' ') buff++;
49      while (*buff && (quote || *buff != ' ')) {
50        if(quote) {
51          if(*buff == quote) quote = 0;
52        } else if(*buff == '"' || *buff == '\'') {
53          quote = *buff;
54        }
55        buff++;
56      }
57      while (*buff == ' ') buff++;
58      n--;
59  }
60  return buff;
61}
62
63/* Return a "nice" version of the path.  Tilde expansion is done, and
64 * duplicate slashes are removed.  Caller must free the return.
65 */
66char *owl_util_makepath(const char *in)
67{
68  int i, j, x;
69  char *out, user[MAXPATHLEN];
70  struct passwd *pw;
71
72  out=owl_malloc(MAXPATHLEN+1);
73  out[0]='\0';
74  j=strlen(in);
75  x=0;
76  for (i=0; i<j; i++) {
77    if (in[i]=='~') {
78      if ( (i==(j-1)) ||          /* last character */
79           (in[i+1]=='/') ) {     /* ~/ */
80        /* use my homedir */
81        pw=getpwuid(getuid());
82        if (!pw) {
83          out[x]=in[i];
84        } else {
85          out[x]='\0';
86          strcat(out, pw->pw_dir);
87          x+=strlen(pw->pw_dir);
88        }
89      } else {
90        /* another user homedir */
91        int a, b;
92        b=0;
93        for (a=i+1; i<j; a++) {
94          if (in[a]==' ' || in[a]=='/') {
95            break;
96          } else {
97            user[b]=in[a];
98            i++;
99            b++;
100          }
101        }
102        user[b]='\0';
103        pw=getpwnam(user);
104        if (!pw) {
105          out[x]=in[i];
106        } else {
107          out[x]='\0';
108          strcat(out, pw->pw_dir);
109          x+=strlen(pw->pw_dir);
110        }
111      }
112    } else if (in[i]=='/') {
113      /* check for a double / */
114      if (i<(j-1) && (in[i+1]=='/')) {
115        /* do nothing */
116      } else {
117        out[x]=in[i];
118        x++;
119      }
120    } else {
121      out[x]=in[i];
122      x++;
123    }
124  }
125  out[x]='\0';
126  return(out);
127}
128
129void atokenize_delete(char **tok, int nels)
130{
131  int i;
132  for (i=0; i<nels; i++) {
133    owl_free(tok[i]);
134  }
135  owl_free(tok);
136}
137
138
139void owl_parse_delete(char **argv, int argc)
140{
141  int i;
142
143  if (!argv) return;
144 
145  for (i=0; i<argc; i++) {
146    if (argv[i]) owl_free(argv[i]);
147  }
148  owl_free(argv);
149}
150
151char **owl_parseline(const char *line, int *argc)
152{
153  /* break a command line up into argv, argc.  The caller must free
154     the returned values.  If there is an error argc will be set to
155     -1, argv will be NULL and the caller does not need to free
156     anything */
157
158  char **argv;
159  int i, len, between=1;
160  char *curarg;
161  char quote;
162
163  argv=owl_malloc(sizeof(char *));
164  len=strlen(line);
165  curarg=owl_malloc(len+10);
166  strcpy(curarg, "");
167  quote='\0';
168  *argc=0;
169  for (i=0; i<len+1; i++) {
170    /* find the first real character */
171    if (between) {
172      if (line[i]==' ' || line[i]=='\t' || line[i]=='\0') {
173        continue;
174      } else {
175        between=0;
176        i--;
177        continue;
178      }
179    }
180
181    /* deal with a quote character */
182    if (line[i]=='"' || line[i]=="'"[0]) {
183      /* if this type of quote is open, close it */
184      if (quote==line[i]) {
185        quote='\0';
186        continue;
187      }
188
189      /* if no quoting is open then open with this */
190      if (quote=='\0') {
191        quote=line[i];
192        continue;
193      }
194
195      /* if another type of quote is open then treat this as a literal */
196      curarg[strlen(curarg)+1]='\0';
197      curarg[strlen(curarg)]=line[i];
198      continue;
199    }
200
201    /* if it's not a space or end of command, then use it */
202    if (line[i]!=' ' && line[i]!='\t' && line[i]!='\n' && line[i]!='\0') {
203      curarg[strlen(curarg)+1]='\0';
204      curarg[strlen(curarg)]=line[i];
205      continue;
206    }
207
208    /* otherwise, if we're not in quotes, add the whole argument */
209    if (quote=='\0') {
210      /* add the argument */
211      argv=owl_realloc(argv, sizeof(char *)*((*argc)+1));
212      argv[*argc] = owl_strdup(curarg);
213      *argc=*argc+1;
214      strcpy(curarg, "");
215      between=1;
216      continue;
217    }
218
219    /* if it is a space and we're in quotes, then use it */
220    curarg[strlen(curarg)+1]='\0';
221    curarg[strlen(curarg)]=line[i];
222  }
223
224  owl_free(curarg);
225
226  /* check for unbalanced quotes */
227  if (quote!='\0') {
228    owl_parse_delete(argv, *argc);
229    *argc=-1;
230    return(NULL);
231  }
232
233  return(argv);
234}
235
236/* caller must free the return */
237char *owl_util_minutes_to_timestr(int in)
238{
239  int days, hours;
240  long run;
241  char *out;
242
243  run=in;
244
245  days=run/1440;
246  run-=days*1440;
247  hours=run/60;
248  run-=hours*60;
249
250  if (days>0) {
251    out=owl_sprintf("%i d %2.2i:%2.2li", days, hours, run);
252  } else {
253    out=owl_sprintf("    %2.2i:%2.2li", hours, run);
254  }
255  return(out);
256}
257
258/* hooks for doing memory allocation et. al. in owl */
259
260void *owl_malloc(size_t size)
261{
262  return(g_malloc(size));
263}
264
265void owl_free(void *ptr)
266{
267  g_free(ptr);
268}
269
270char *owl_strdup(const char *s1)
271{
272  return(g_strdup(s1));
273}
274
275void *owl_realloc(void *ptr, size_t size)
276{
277  return(g_realloc(ptr, size));
278}
279
280/* allocates memory and returns the string or null.
281 * caller must free the string.
282 */
283char *owl_sprintf(const char *fmt, ...)
284{
285  va_list ap;
286  char *ret = NULL;
287  va_start(ap, fmt);
288  ret = g_strdup_vprintf(fmt, ap);
289  va_end(ap);
290  return ret;
291}
292
293/* These are in order of their value in owl.h */
294static const struct {
295  int number;
296  const char *name;
297} color_map[] = {
298  {OWL_COLOR_INVALID, "invalid"},
299  {OWL_COLOR_DEFAULT, "default"},
300  {OWL_COLOR_BLACK, "black"},
301  {OWL_COLOR_RED, "red"},
302  {OWL_COLOR_GREEN, "green"},
303  {OWL_COLOR_YELLOW,"yellow"},
304  {OWL_COLOR_BLUE, "blue"},
305  {OWL_COLOR_MAGENTA, "magenta"},
306  {OWL_COLOR_CYAN, "cyan"},
307  {OWL_COLOR_WHITE, "white"},
308};
309
310/* Return the owl color associated with the named color.  Return -1
311 * if the named color is not available
312 */
313int owl_util_string_to_color(const char *color)
314{
315  int c, i;
316  char *p;
317
318  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
319    if (strcasecmp(color, color_map[i].name) == 0)
320      return color_map[i].number;
321
322  c = strtol(color, &p, 10);
323  if (p != color && c >= -1 && c < COLORS) {
324    return(c);
325  }
326  return(OWL_COLOR_INVALID);
327}
328
329/* Return a string name of the given owl color */
330const char *owl_util_color_to_string(int color)
331{
332  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
333    return color_map[color - OWL_COLOR_INVALID].name;
334  return("Unknown color");
335}
336
337/* Get the default tty name.  Caller must free the return */
338char *owl_util_get_default_tty(void)
339{
340  const char *tmp;
341  char *out;
342
343  if (getenv("DISPLAY")) {
344    out=owl_strdup(getenv("DISPLAY"));
345  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
346    out=owl_strdup(tmp);
347    if (!strncmp(out, "/dev/", 5)) {
348      owl_free(out);
349      out=owl_strdup(tmp+5);
350    }
351  } else {
352    out=owl_strdup("unknown");
353  }
354  return(out);
355}
356
357/* strip leading and trailing new lines.  Caller must free the
358 * return.
359 */
360char *owl_util_stripnewlines(const char *in)
361{
362 
363  char  *tmp, *ptr1, *ptr2, *out;
364
365  ptr1=tmp=owl_strdup(in);
366  while (ptr1[0]=='\n') {
367    ptr1++;
368  }
369  ptr2=ptr1+strlen(ptr1)-1;
370  while (ptr2>ptr1 && ptr2[0]=='\n') {
371    ptr2[0]='\0';
372    ptr2--;
373  }
374
375  out=owl_strdup(ptr1);
376  owl_free(tmp);
377  return(out);
378}
379
380
381/* If filename is a link, recursively resolve symlinks.  Otherwise, return the filename
382 * unchanged.  On error, call owl_function_error and return NULL.
383 *
384 * This function assumes that filename eventually resolves to an acutal file.
385 * If you want to check this, you should stat() the file first.
386 *
387 * The caller of this function is responsible for freeing the return value.
388 *
389 * Error conditions are the same as g_file_read_link.
390 */
391gchar *owl_util_recursive_resolve_link(const char *filename)
392{
393  gchar *last_path = g_strdup(filename);
394  GError *err = NULL;
395
396  while (g_file_test(last_path, G_FILE_TEST_IS_SYMLINK)) {
397    gchar *link_path = g_file_read_link(last_path, &err);
398    if (link_path == NULL) {
399      owl_function_error("Cannot resolve symlink %s: %s",
400                         last_path, err->message);
401      g_error_free(err);
402      g_free(last_path);
403      return NULL;
404    }
405
406    /* Deal with obnoxious relative paths. If we really care, all this
407     * is racy. Whatever. */
408    if (!g_path_is_absolute(link_path)) {
409      char *last_dir = g_path_get_dirname(last_path);
410      char *tmp = g_build_path(G_DIR_SEPARATOR_S,
411                               last_dir,
412                               link_path,
413                               NULL);
414      g_free(last_dir);
415      g_free(link_path);
416      link_path = tmp;
417    }
418
419    g_free(last_path);
420    last_path = link_path;
421  }
422  return last_path;
423}
424
425/* Delete all lines matching "line" from the named file.  If no such
426 * line is found the file is left intact.  If backup==1 then leave a
427 * backup file containing the original contents.  The match is
428 * case-insensitive.
429 *
430 * Returns the number of lines removed on success.  Returns -1 on failure.
431 */
432int owl_util_file_deleteline(const char *filename, const char *line, int backup)
433{
434  char *backupfile, *newfile, *buf = NULL;
435  gchar *actual_filename; /* gchar; we need to g_free it */
436  FILE *old, *new;
437  struct stat st;
438  int numremoved = 0;
439
440  if ((old = fopen(filename, "r")) == NULL) {
441    owl_function_error("Cannot open %s (for reading): %s",
442                       filename, strerror(errno));
443    return -1;
444  }
445
446  if (fstat(fileno(old), &st) != 0) {
447    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
448    return -1;
449  }
450
451  /* resolve symlinks, because link() fails on symlinks, at least on AFS */
452  actual_filename = owl_util_recursive_resolve_link(filename);
453  if (actual_filename == NULL)
454    return -1; /* resolving the symlink failed, but we already logged this error */
455
456  newfile = owl_sprintf("%s.new", actual_filename);
457  if ((new = fopen(newfile, "w")) == NULL) {
458    owl_function_error("Cannot open %s (for writing): %s",
459                       actual_filename, strerror(errno));
460    owl_free(newfile);
461    fclose(old);
462    free(actual_filename);
463    return -1;
464  }
465
466  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
467    owl_function_error("Cannot set permissions on %s: %s",
468                       actual_filename, strerror(errno));
469    unlink(newfile);
470    fclose(new);
471    owl_free(newfile);
472    fclose(old);
473    free(actual_filename);
474    return -1;
475  }
476
477  while (owl_getline_chomp(&buf, old))
478    if (strcasecmp(buf, line) != 0)
479      fprintf(new, "%s\n", buf);
480    else
481      numremoved++;
482  owl_free(buf);
483
484  fclose(new);
485  fclose(old);
486
487  if (backup) {
488    backupfile = owl_sprintf("%s.backup", actual_filename);
489    unlink(backupfile);
490    if (link(actual_filename, backupfile) != 0) {
491      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
492      owl_free(backupfile);
493      unlink(newfile);
494      owl_free(newfile);
495      return -1;
496    }
497    owl_free(backupfile);
498  }
499
500  if (rename(newfile, actual_filename) != 0) {
501    owl_function_error("Cannot move %s to %s: %s",
502                       newfile, actual_filename, strerror(errno));
503    numremoved = -1;
504  }
505
506  unlink(newfile);
507  owl_free(newfile);
508
509  g_free(actual_filename);
510
511  return numremoved;
512}
513
514int owl_util_max(int a, int b)
515{
516  if (a>b) return(a);
517  return(b);
518}
519
520int owl_util_min(int a, int b)
521{
522  if (a<b) return(a);
523  return(b);
524}
525
526/* Return the base class or instance from a zephyr class, by removing
527   leading `un' or trailing `.d'.
528   The caller is responsible for freeing the allocated string.
529*/
530char * owl_util_baseclass(const char * class)
531{
532  char *start, *end;
533
534  while(!strncmp(class, "un", 2)) {
535    class += 2;
536  }
537
538  start = owl_strdup(class);
539  end = start + strlen(start) - 1;
540  while(end > start && *end == 'd' && *(end-1) == '.') {
541    end -= 2;
542  }
543  *(end + 1) = 0;
544
545  return start;
546}
547
548const char * owl_get_datadir(void)
549{
550  const char * datadir = getenv("BARNOWL_DATA_DIR");
551  if(datadir != NULL)
552    return datadir;
553  return DATADIR;
554}
555
556const char * owl_get_bindir(void)
557{
558  const char * bindir = getenv("BARNOWL_BIN_DIR");
559  if(bindir != NULL)
560    return bindir;
561  return BINDIR;
562}
563
564/* Strips format characters from a valid utf-8 string. Returns the
565   empty string if 'in' does not validate. */
566char * owl_strip_format_chars(const char *in)
567{
568  char *r;
569  if (g_utf8_validate(in, -1, NULL)) {
570    const char *s, *p;
571    r = owl_malloc(strlen(in)+1);
572    r[0] = '\0';
573    s = in;
574    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
575    while(p) {
576      /* If it's a format character, copy up to it, and skip all
577         immediately following format characters. */
578      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
579        strncat(r, s, p-s);
580        p = g_utf8_next_char(p);
581        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
582          p = g_utf8_next_char(p);
583        }
584        s = p;
585        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
586      }
587      else {
588        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
589      }
590    }
591    if (s) strcat(r,s);
592  }
593  else {
594    r = owl_strdup("");
595  }
596  return r;
597}
598
599/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
600 * the caller to specify an alternative in the future. We also strip
601 * out characters in Unicode Plane 16, as we use that plane internally
602 * for formatting.
603 */
604char * owl_validate_or_convert(const char *in)
605{
606  if (g_utf8_validate(in, -1, NULL)) {
607    return owl_strip_format_chars(in);
608  }
609  else {
610    return g_convert(in, -1,
611                     "UTF-8", "ISO-8859-1",
612                     NULL, NULL, NULL);
613  }
614}
615/*
616 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
617 * string if it is invalid utf-8.
618 */
619char * owl_validate_utf8(const char *in)
620{
621  char *out;
622  if (g_utf8_validate(in, -1, NULL)) {
623    out = owl_strdup(in);
624  } else {
625    out = owl_strdup("");
626  }
627  return out;
628}
629
630/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
631int owl_util_can_break_after(gunichar c)
632{
633 
634  if (c == ' ') return 1;
635  if (c >= 0x3000 && c <= 0x312f) {
636    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
637    if (c == 0x300a || c == 0x300c || c == 0x300e ||
638        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
639        c == 0x3018 || c == 0x301a)
640      return 0;
641    return 1;
642  }
643  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
644  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
645  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
646  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
647  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
648  return 0;
649}
650
651char *owl_escape_highbit(const char *str)
652{
653  GString *out = g_string_new("");
654  unsigned char c;
655  while((c = (*str++))) {
656    if(c == '\\') {
657      g_string_append(out, "\\\\");
658    } else if(c & 0x80) {
659      g_string_append_printf(out, "\\x%02x", (int)c);
660    } else {
661      g_string_append_c(out, c);
662    }
663  }
664  return g_string_free(out, 0);
665}
666
667/* innards of owl_getline{,_chomp} below */
668static int owl_getline_internal(char **s, FILE *fp, int newline)
669{
670  int size = 0;
671  int target = 0;
672  int count = 0;
673  int c;
674
675  while (1) {
676    c = getc(fp);
677    if ((target + 1) > size) {
678      size += BUFSIZ;
679      *s = owl_realloc(*s, size);
680    }
681    if (c == EOF)
682      break;
683    count++;
684    if (c != '\n' || newline)
685        (*s)[target++] = c;
686    if (c == '\n')
687      break;
688  }
689  (*s)[target] = 0;
690
691  return count;
692}
693
694/* Read a line from fp, allocating memory to hold it, returning the number of
695 * byte read.  *s should either be NULL or a pointer to memory allocated with
696 * owl_malloc; it will be owl_realloc'd as appropriate.  The caller must
697 * eventually free it.  (This is roughly the interface of getline in the gnu
698 * libc).
699 *
700 * The final newline will be included if it's there.
701 */
702int owl_getline(char **s, FILE *fp)
703{
704  return owl_getline_internal(s, fp, 1);
705}
706
707/* As above, but omitting the final newline */
708int owl_getline_chomp(char **s, FILE *fp)
709{
710  return owl_getline_internal(s, fp, 0);
711}
712
713/* Read the rest of the input available in fp into a string. */
714char *owl_slurp(FILE *fp)
715{
716  char *buf = NULL;
717  char *p;
718  int size = 0;
719  int count;
720
721  while (1) {
722    buf = owl_realloc(buf, size + BUFSIZ);
723    p = &buf[size];
724    size += BUFSIZ;
725
726    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
727      break;
728  }
729  p[count] = 0;
730
731  return buf;
732}
733
734gulong owl_dirty_window_on_signal(owl_window *w, gpointer sender, const gchar *detailed_signal)
735{
736  return owl_signal_connect_object(sender, detailed_signal, G_CALLBACK(owl_window_dirty), w, G_CONNECT_SWAPPED);
737}
738
739typedef struct { /*noproto*/
740  GObject  *sender;
741  gulong    signal_id;
742} SignalData;
743
744static void _closure_invalidated(gpointer data, GClosure *closure);
745
746/*
747 * GObject's g_signal_connect_object has a documented bug. This function is
748 * identical except it does not leak the signal handler.
749 */
750gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
751{
752  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
753  g_return_val_if_fail (detailed_signal != NULL, 0);
754  g_return_val_if_fail (c_handler != NULL, 0);
755
756  if (receiver) {
757    SignalData *sdata;
758    GClosure *closure;
759    gulong signal_id;
760
761    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
762
763    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
764    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
765
766    /* Register the missing hooks */
767    sdata = g_slice_new0(SignalData);
768    sdata->sender = sender;
769    sdata->signal_id = signal_id;
770
771    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
772
773    return signal_id;
774  } else {
775    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
776  }
777}
778
779/*
780 * There are three ways the signal could come to an end:
781 *
782 * 1. The user explicitly disconnects it with the returned signal_id.
783 *    - In that case, the disconnection unref's the closure, causing it
784 *      to first be invalidated. The handler's already disconnected, so
785 *      we have no work to do.
786 * 2. The sender gets destroyed.
787 *    - GObject will disconnect each signal which then goes into the above
788 *      case. Our handler does no work.
789 * 3. The receiver gets destroyed.
790 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
791 *      invalidated when the receiver is destroyed. We then follow through case 1
792 *      again, but *this* time, the handler has not been disconnected. We then
793 *      clean up ourselves.
794 *
795 * We can't actually hook into this process earlier with weakrefs as GObject
796 * will, on object dispose, first disconnect signals, then invalidate closures,
797 * and notify weakrefs last.
798 */
799static void _closure_invalidated(gpointer data, GClosure *closure)
800{
801  SignalData *sdata = data;
802  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
803    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
804  }
805  g_slice_free(SignalData, sdata);
806}
807
Note: See TracBrowser for help on using the repository browser.