summaryrefslogtreecommitdiffstats
path: root/src/util.c
blob: f8ff05ed5dc6b82195a5f31582a4601ec547b43f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* $Id$ */

/***
  This file is part of libnewmail

  libnewmail is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
  
  libnewmail is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with libnewmail; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  USA
***/

#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>

#include "util.h"
#include "newmail.h"

char* nm_chomp(char *ln) {
    if (!ln)
        return NULL;
    ln[strcspn(ln, "\n\r\0")] = 0;
    return ln;
}

char* nm_specials(const char *format) {
    int i;
    static char ret[PATH_MAX];
    const char *p;
    char *d;
    int special=0, max;

    if (!format)
        return NULL;
    
    max = PATH_MAX-1;
    ret[max] = 0;

    memset(ret, 0, max);
    
    for (p = format, d = ret, i=0; *p && i < max; p++) {
        //fprintf(stderr, "CHAR: %c [%s] %s\n", *p, ret, special ? "SPEC" : "");
        if (special) {
            char *a = NULL;
            if (*p == 'u')
                a = getenv("USER");
            else if (*p == 'h')
                a = getenv("HOME");
            else if (*p == 'H') {
                static char hn[256];
                gethostname(a = hn, sizeof(hn));
            }
                            
            if (a) {
                int x;
                special = 0;
                strncpy(d, a, max-i);
                x = strlen(d);
                d += x; i += x;
                continue;
            }
        } else if (*p == '%') {
            special = 1;
            continue;
        }

        special = 0;
        *d = *p;
        d++; i++;
    }

    return ret;
}


char *nm_strdup(const char *s) {
    char *p;
    if (!s)
        return 0;
    p = nm_malloc(strlen(s)+1);
    return p ? strcpy(p, s) : 0;
}

void nm_error(enum nm_error en, const char* exp) {
    nm_errno = en | (exp ? NM_ERROR_EXPLANATION : 0);
    if (nm_explanation)
        nm_free((void*) nm_explanation);
    nm_explanation = nm_strdup(exp);
}