b4b96b7bbff47c78bd5f77e1200ab9a15669fcee
[oftp] / src / util.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "util.h"
5 #include "tui.h"
6
7 void *malloc_nf_impl(size_t sz, const char *file, int line)
8 {
9         void *p;
10         if(!(p = malloc(sz))) {
11                 fprintf(stderr, "%s:%d failed to allocate %lu bytes\n", file, line, (unsigned long)sz);
12                 abort();
13         }
14         return p;
15 }
16
17 void *calloc_nf_impl(size_t num, size_t sz, const char *file, int line)
18 {
19         void *p;
20         if(!(p = calloc(num, sz))) {
21                 fprintf(stderr, "%s:%d failed to allocate %lu bytes\n", file, line, (unsigned long)(sz * num));
22                 abort();
23         }
24         return p;
25 }
26
27 void *realloc_nf_impl(void *p, size_t sz, const char *file, int line)
28 {
29         if(!(p = realloc(p, sz))) {
30                 fprintf(stderr, "%s:%d failed to realloc %lu bytes\n", file, line, (unsigned long)sz);
31                 abort();
32         }
33         return p;
34 }
35
36 char *strdup_nf_impl(const char *s, const char *file, int line)
37 {
38         char *res;
39         if(!(res = strdup(s))) {
40                 fprintf(stderr, "%s:%d failed to duplicate string\n", file, line);
41                 abort();
42         }
43         return res;
44 }
45
46
47 int match_prefix(const char *str, const char *prefix)
48 {
49         while(*str && *prefix) {
50                 if(*str++ != *prefix++) {
51                         return 0;
52                 }
53         }
54         return *prefix ? 0 : 1;
55 }
56
57 static FILE *logfile;
58
59 static void closelog(void)
60 {
61         fclose(logfile);
62 }
63
64 static void logmsg(const char *tag, const char *fmt, va_list ap)
65 {
66         if(!logfile) {
67                 if(!(logfile = fopen("oftp.log", "w"))) {
68                         return;
69                 }
70                 setvbuf(logfile, 0, _IOLBF, 0);
71                 atexit(closelog);
72         }
73         fprintf(logfile, "%s: ", tag);
74         vfprintf(logfile, fmt, ap);
75 }
76
77 void errmsg(const char *fmt, ...)
78 {
79         va_list ap;
80
81         va_start(ap, fmt);
82         tui_vmsgbox(TUI_ERROR, "error", fmt, ap);
83         va_end(ap);
84
85         va_start(ap, fmt);
86         logmsg("error", fmt, ap);
87         va_end(ap);
88 }
89
90 void warnmsg(const char *fmt, ...)
91 {
92         va_list ap;
93
94         va_start(ap, fmt);
95         tui_status(TUI_WARN, fmt, ap);
96         va_end(ap);
97
98         va_start(ap, fmt);
99         logmsg("warning", fmt, ap);
100         va_end(ap);
101 }
102
103 void infomsg(const char *fmt, ...)
104 {
105         va_list ap;
106
107         va_start(ap, fmt);
108         tui_status(TUI_INFO, fmt, ap);
109         va_end(ap);
110
111         va_start(ap, fmt);
112         logmsg("info", fmt, ap);
113         va_end(ap);
114 }