2 * tools.c -- Miscellaneous routines
13 #include <sys/types.h>
15 #include <sys/socket.h>
18 #include <netinet/in.h>
31 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
32 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
36 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
40 char *safestrncpy(char *dest, const char *src, size_t n)
42 if (dest == NULL || src == NULL) {
43 fprintf(stderr, "safestrncpy: NULL argument\n");
46 strncpy(dest, src, n);
54 * num_tokens() - discover number of parameters/tokens in a string
56 int num_tokens(char *source, char tok) {
60 if (source == NULL) return(0);
61 for (a=0; a<strlen(source); ++a) {
62 if (source[a]==tok) ++count;
68 * extract_token() - a smarter string tokenizer
70 void extract_token(char *dest, char *source, int parmnum, char separator)
80 if (strlen(source)==0) {
84 for (i=0; i<strlen(source); ++i) {
85 if (source[i]==separator) {
88 else if (curr_parm == parmnum) {
90 dest[len++] = source[i];
98 * remove_token() - a tokenizer that kills, maims, and destroys
100 void remove_token(char *source, int parmnum, char separator)
112 if (strlen(source)==0) {
116 for (i=0; i<strlen(source); ++i) {
117 if ( (start < 0) && (curr_parm == parmnum) ) {
121 if ( (end < 0) && (curr_parm == (parmnum+1)) ) {
125 if (source[i]==separator) {
130 if (end < 0) end = strlen(source);
132 printf("%d .. %d\n", start, end);
134 strcpy(&source[start], &source[end]);
141 * extract_int() - extract an int parm w/o supplying a buffer
143 int extract_int(char *source, int parmnum)
147 extract_token(buf, source, parmnum, '|');
152 * extract_long() - extract an long parm w/o supplying a buffer
154 long extract_long(char *source, long int parmnum)
158 extract_token(buf, source, parmnum, '|');
177 * check for the presence of a character within a string (returns count)
185 for (a = 0; a < strlen(st); ++a)
193 * Format a date/time stamp for output
195 void fmt_date(char *buf, time_t thetime) {
199 tm = localtime(&thetime);
201 sprintf(buf, "%s %d %d %2d:%02d%s",
202 ascmonths[tm->tm_mon],
205 ( (tm->tm_hour > 12) ? (tm->tm_hour - 12) : (tm->tm_hour) ),
207 ( (tm->tm_hour > 12) ? "pm" : "am" )
215 * Format a date/time stamp to the format used in HTTP headers
217 void httpdate(char *buf, time_t thetime) {
221 tm = localtime(&thetime);
223 sprintf(buf, "%s, %02d %s %4d %02d:%02d:%02d",
224 ascdays[tm->tm_wday],
226 ascmonths[tm->tm_mon],
239 * Utility function to "readline" from memory
240 * (returns new pointer)
242 char *memreadline(char *start, char *buf, int maxlen)
246 int len = 0; /* tally our own length to avoid strlen() delays */
249 memset(buf, 0, maxlen);
253 if ( (len < (maxlen - 1)) && (ch != 13) && (ch != 10) ) {
254 buf[strlen(buf) + 1] = 0;
255 buf[strlen(buf)] = ch;
258 if ((ch == 10) || (ch == 0)) {