6a9ab4e8a48913be4f1f7c692d31a2d3cbf1070d
[sip-router] / parser / parse_expires.c
1 /*
2  * $Id$
3  *
4  * Expires header field body parser
5  */
6
7 #include "parse_expires.h"
8 #include <stdio.h>          /* printf */
9 #include "../mem/mem.h"     /* pkg_malloc, pkg_free */
10 #include "../dprint.h"
11 #include "../trim.h"        /* trim_leading */
12 #include <string.h>         /* memset */
13
14
15 static inline int expires_parser(char* _s, int _l, exp_body_t* _e)
16 {
17         int i;
18         str tmp;
19         
20         tmp.s = _s;
21         tmp.len = _l;
22
23         trim_leading(&tmp);
24
25         if (tmp.len == 0) {
26                 LOG(L_ERR, "expires_parser(): Empty body\n");
27                 return -1;
28         }
29
30         _e->text.s = tmp.s;
31
32         for(i = 0; i < tmp.len; i++) {
33                 if ((tmp.s[i] >= '0') && (tmp.s[i] <= '9')) {
34                         _e->val *= 10;
35                         _e->val += tmp.s[i] - '0';
36                 } else {
37                         switch(tmp.s[i]) {
38                         case ' ':
39                         case '\t':
40                         case '\r':
41                         case '\n':
42                                 _e->text.len = i;
43                                 return 0;
44
45                         default:
46                                 LOG(L_ERR, "expires_parser(): Invalid character\n");
47                                 return -2;
48                         }
49                 }
50         }
51
52         _e->text.len = _l;
53         return 0;
54 }
55
56
57 /*
58  * Parse expires header field body
59  */
60 int parse_expires(struct hdr_field* _h)
61 {
62         exp_body_t* e;
63
64         if (_h->parsed) {
65                 return 0;  /* Already parsed */
66         }
67
68         e = (exp_body_t*)pkg_malloc(sizeof(exp_body_t));
69         if (e == 0) {
70                 LOG(L_ERR, "parse_expires(): No memory left\n");
71                 return -1;
72         }
73         
74         memset(e, 0, sizeof(exp_body_t));
75
76         if (expires_parser(_h->body.s, _h->body.len, e) < 0) {
77                 LOG(L_ERR, "parse_expires(): Error while parsing\n");
78                 pkg_free(e);
79                 return -2;
80         }
81         
82         _h->parsed = (void*)e;
83         return 0;
84 }
85
86
87 /*
88  * Free all memory associated with exp_body_t
89  */
90 void free_expires(exp_body_t** _e)
91 {
92         pkg_free(*_e);
93         *_e = 0;
94 }
95
96
97 /*
98  * Print exp_body_t content, for debugging only
99  */
100 void print_expires(exp_body_t* _e)
101 {
102         printf("===Expires===\n");
103         printf("text: \'%.*s\'\n", _e->text.len, _e->text.s);
104         printf("val : %d\n", _e->val);
105         printf("===/Expires===\n");
106 }