1 /*
2  * Copyright (C) 2001-2003 FhG Fokus
3  *
4  * This file is part of Kamailio, a free SIP server.
5  *
6  * Kamailio is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version
10  *
11  * Kamailio is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21 
22 /*! \file
23  * \brief Parser :: ???
24  *
25  * \ingroup parser
26  */
27 
28 
29 #ifndef msg_parser_h
30 #define msg_parser_h
31 
32 
33 #include "../comp_defs.h"
34 #include "../str.h"
35 #include "../lump_struct.h"
36 #include "../flags.h"
37 #include "../ip_addr.h"
38 #include "../config.h"
39 #include "parse_def.h"
40 #include "parse_cseq.h"
41 #include "parse_via.h"
42 #include "parse_fline.h"
43 #include "parse_retry_after.h"
44 #include "hf.h"
45 #include "../error.h"
46 
47 
48 /*! \name convenience short-cut macros */
49 /*@{ */
50 #define REQ_LINE(_msg) ((_msg)->first_line.u.request)
51 #define REQ_METHOD first_line.u.request.method_value
52 #define REPLY_STATUS first_line.u.reply.statuscode
53 #define REPLY_CLASS(_reply) ((_reply)->REPLY_STATUS/100)
54 /*@} */
55 
56 /*! \brief start of "actual" sip msg (start of first line) */
57 #define SIP_MSG_START(m)	((m)->first_line.u.request.method.s)
58 
59 /*! \brief number methods as power of two to allow bitmap matching */
60 typedef enum request_method {
61 	METHOD_UNDEF=0,           /*!< 0 - --- */
62 	METHOD_INVITE=1,          /*!< 1 - 2^0 */
63 	METHOD_CANCEL=2,          /*!< 2 - 2^1 */
64 	METHOD_ACK=4,             /*!< 4 - 2^2 */
65 	METHOD_BYE=8,             /*!< 8 - 2^3 */
66 	METHOD_INFO=16,           /*!< 16 - 2^4 */
67 	METHOD_REGISTER=32,       /*!< 32 - 2^5 */
68 	METHOD_SUBSCRIBE=64,      /*!< 64 - 2^6 */
69 	METHOD_NOTIFY=128,        /*!< 128 - 2^7 */
70 	METHOD_MESSAGE=256,       /*!< 256 - 2^8 */
71 	METHOD_OPTIONS=512,       /*!< 512 - 2^9 */
72 	METHOD_PRACK=1024,        /*!< 1024 - 2^10 */
73 	METHOD_UPDATE=2048,       /*!< 2048 - 2^11 */
74 	METHOD_REFER=4096,        /*!< 4096 - 2^12 */
75 	METHOD_PUBLISH=8192,      /*!< 8192 - 2^13 */
76 	METHOD_KDMQ=16384,        /*!< 16384 - 2^14 */
77 	METHOD_GET=32768,         /*!< 32768 - 2^15 */
78 	METHOD_POST=65536,        /*!< 65536 - 2^16 */
79 	METHOD_PUT=131072,        /*!< 131072 - 2^17 */
80 	METHOD_DELETE=262144,     /*!< 262144 - 2^18 */
81 	METHOD_OTHER=524288       /*!< 524288 - 2^19 */
82 } request_method_t;
83 
84 #define FL_FORCE_RPORT  (1 << 0)  /*!< force rport */
85 #define FL_FORCE_ACTIVE (1 << 1)  /*!< force active SDP */
86 #define FL_SDP_IP_AFS   (1 << 2)  /*!< SDP IP rewritten */
87 #define FL_SDP_PORT_AFS (1 << 3)  /*!< SDP port rewritten */
88 #define FL_SHM_CLONE    (1 << 4)  /*!< msg cloned in SHM as a single chunk */
89 #define FL_TIMEOUT      (1 << 5)  /*!< message belongs to an "expired" branch
90 									(for failure route use) */
91 #define FL_REPLIED      (1 << 6)  /*!< message branch received at least one reply
92 									(for failure route use) */
93 #define FL_HASH_INDEX   (1 << 7)  /*!< msg->hash_index contains a valid value (tm use)*/
94 
95 #define FL_MTU_TCP_FB   (1 << 8)
96 #define FL_MTU_TLS_FB   (1 << 9)
97 #define FL_MTU_SCTP_FB  (1 << 10)
98 #define FL_ADD_LOCAL_RPORT  (1 << 11) /*!< add 'rport' to local via hdr */
99 #define FL_SDP_BODY     (1 << 12)  /*!< msg has SDP in body */
100 #define FL_USE_UAC_FROM      (1<<13)  /* take FROM hdr from UAC instead of UAS*/
101 #define FL_USE_UAC_TO        (1<<14)  /* take TO hdr from UAC instead of UAS */
102 #define FL_TM_RPL_MATCHED    (1<<15)  /* tm matched reply already */
103 #define FL_RPL_SUSPENDED     (1<<16)  /* for async reply processing */
104 #define FL_BODY_MULTIPART    (1<<17)  /* body modified is multipart */
105 #define FL_RR_ADDED          (1<<18)  /* Record-Route header was added */
106 #define FL_UAC_AUTH          (1<<19)  /* Proxy UAC-like authentication */
107 #define FL_ADD_SRVID         (1<<20) /*!< add 'srvid' to local via hdr */
108 #define FL_ADD_XAVP_VIA_PARAMS (1<<21) /*!< add xavp fields to local via params */
109 #define FL_USE_XAVP_VIA_FIELDS (1<<22) /*!< use xavp fields for local via attrs */
110 #define FL_MSG_NOREPLY       (1<<23) /*!< do not send sip reply for request */
111 #define FL_SIPTRACE          (1<<24) /*!< message to be traced in stateless replies */
112 #define FL_ROUTE_ADDR        (1<<25) /*!< request has Route address for next hop */
113 #define FL_USE_OTCPID        (1<<26) /*!< request to be routed using outboud tcp con id */
114 
115 /* WARNING: Value (1 << 28) is reserved for use in kamailio call_control
116  * module (flag  FL_USE_CALL_CONTROL )! */
117 
118 /* WARNING: Value (1 << 29) is reserved for use in kamailio acc
119  * module (flag FL_REQ_UPSTREAM)! */
120 
121 /* WARNING: Value (1 << 30) is reserved for use in kamailio
122  * media proxy module (flag FL_USE_MEDIA_PROXY)! */
123 
124 /* WARNING: Value (1 << 31) is reserved for use in kamailio
125  * nat_traversal module (flag FL_DO_KEEPALIVE)! */
126 
127 #define FL_MTU_FB_MASK  (FL_MTU_TCP_FB|FL_MTU_TLS_FB|FL_MTU_SCTP_FB)
128 
129 
130 #define IFISMETHOD(methodname,firstchar)                                  \
131 if (  (*tmp==(firstchar) || *tmp==((firstchar) | 32)) &&                  \
132 		strncasecmp( tmp+1, &#methodname[1], methodname##_LEN-1)==0 &&     \
133 		*(tmp+methodname##_LEN)==' ') {                                   \
134 				fl->type=SIP_REQUEST;                                     \
135 				fl->u.request.method.len=methodname##_LEN;                \
136 				fl->u.request.method_value=METHOD_##methodname;           \
137 				tmp=buffer+methodname##_LEN;                              \
138 }
139 
140 #define IS_HTTP(req)                                                \
141 	((req)->first_line.u.request.version.len >= HTTP_VERSION_LEN && \
142 	!strncasecmp((req)->first_line.u.request.version.s,             \
143 		HTTP_VERSION, HTTP_VERSION_LEN))
144 
145 #define IS_SIP(req)                                                \
146 	((req)->first_line.u.request.version.len >= SIP_VERSION_LEN && \
147 	!strncasecmp((req)->first_line.u.request.version.s,             \
148 		SIP_VERSION, SIP_VERSION_LEN))
149 
150 #define IS_HTTP_REPLY(rpl)                                                \
151 	(((rpl)->first_line.u.reply.version.len >= HTTP_VERSION_LEN && \
152 	!strncasecmp((rpl)->first_line.u.reply.version.s,             \
153 		HTTP_VERSION, HTTP_VERSION_LEN)) ||                         \
154 	((rpl)->first_line.u.reply.version.len >= HTTP2_VERSION_LEN && \
155 	!strncasecmp((rpl)->first_line.u.reply.version.s,             \
156 		HTTP2_VERSION, HTTP2_VERSION_LEN)))
157 
158 #define IS_SIP_REPLY(rpl)                                                \
159 	((rpl)->first_line.u.reply.version.len >= SIP_VERSION_LEN && \
160 	!strncasecmp((rpl)->first_line.u.reply.version.s,             \
161 		SIP_VERSION, SIP_VERSION_LEN))
162 
163 /*! \brief
164  * Return a URI to which the message should be really sent (not what should
165  * be in the Request URI. The following fields are tried in this order:
166  * 1) dst_uri
167  * 2) new_uri
168  * 3) first_line.u.request.uri
169  */
170 #define GET_NEXT_HOP(m) \
171 (((m)->dst_uri.s && (m)->dst_uri.len) ? (&(m)->dst_uri) : \
172 (((m)->new_uri.s && (m)->new_uri.len) ? (&(m)->new_uri) : (&(m)->first_line.u.request.uri)))
173 
174 
175 /*! \brief
176  * Return the Reqeust URI of a message.
177  * The following fields are tried in this order:
178  * 1) new_uri
179  * 2) first_line.u.request.uri
180  */
181 #define GET_RURI(m) \
182 (((m)->new_uri.s && (m)->new_uri.len) ? (&(m)->new_uri) : (&(m)->first_line.u.request.uri))
183 
184 
185 enum _uri_type{ERROR_URI_T=0, SIP_URI_T, SIPS_URI_T, TEL_URI_T, TELS_URI_T, URN_URI_T};
186 typedef enum _uri_type uri_type;
187 enum _uri_flags{
188 	URI_USER_NORMALIZE=1,
189 	URI_SIP_USER_PHONE=2
190 }; /* bit fields */
191 typedef enum _uri_flags uri_flags;
192 
193 /*! \brief The SIP uri object */
194 struct sip_uri {
195 	str user;     /*!< Username */
196 	str passwd;   /*!< Password */
197 	str host;     /*!< Host name */
198 	str port;     /*!< Port number */
199 	str params;   /*!< Parameters */
200 	str sip_params; /*!< Parameters of the sip: URI.
201 					* (If a tel: URI is embedded in a sip: URI, then
202 					* params points to the parameters of the tel: URI,
203 					* and sip_params to the parameters of the sip: URI.
204 					*/
205 	str headers;
206 	unsigned short port_no;
207 	unsigned short proto; /*!< from transport */
208 	uri_type type; /*!< uri scheme */
209 	uri_flags flags;
210 	/*!< parameters */
211 	str transport;
212 	str ttl;
213 	str user_param;
214 	str maddr;
215 	str method;
216 	str lr;
217 	str r2; /*!< ser specific rr parameter */
218 	str gr;
219 	str transport_val; /*!< transport value */
220 	str ttl_val;	 /*!< TTL value */
221 	str user_param_val; /*!< User= param value */
222 	str maddr_val; /*!< Maddr= param value */
223 	str method_val; /*!< Method value */
224 	str lr_val; /*!< lr value placeholder for lr=on a.s.o*/
225 	str r2_val;
226 	str gr_val;
227 #ifdef USE_COMP
228 	unsigned short comp;
229 #endif
230 };
231 
232 typedef struct sip_uri sip_uri_t;
233 
234 struct msg_body;
235 
236 typedef void (*free_msg_body_f)(struct msg_body** ptr);
237 
238 typedef enum msg_body_type {
239 	MSG_BODY_UNKNOWN = 0,
240 	MSG_BODY_SDP
241 } msg_body_type_t;
242 
243 /*! \brief This structure represents a generic SIP message body, regardless of the
244  * body type.
245  *
246  * Body parsers are supposed to cast this structure to some other
247  * body-type specific structure, but the body type specific structure must
248  * retain msg_body_type variable and a pointer to the free function as the
249  * first two variables within the structure.
250  */
251 typedef struct msg_body {
252 	msg_body_type_t type;
253 	free_msg_body_f free;
254 } msg_body_t;
255 
256 
257 /* pre-declaration, to include sys/time.h in .c */
258 struct timeval;
259 
260 /* structure for cached decoded flow for outbound */
261 typedef struct ocd_flow {
262 		int decoded;
263 		struct receive_info rcv;
264 } ocd_flow_t;
265 
266 /* structure holding fields that don't have to be cloned in shm
267  * - its content is memset'ed to in shm clone
268  * - add to msg_ldata_reset() if a field uses dynamic memory */
269 typedef struct msg_ldata {
270 	ocd_flow_t flow;
271 	void *vdata;
272 } msg_ldata_t;
273 
274 /*! \brief The SIP message */
275 typedef struct sip_msg {
276 	unsigned int id;               /*!< message id, unique/process*/
277 	int pid;                       /*!< process id */
278 	struct timeval tval;           /*!< time value associated to message */
279 	snd_flags_t fwd_send_flags;    /*!< send flags for forwarding */
280 	snd_flags_t rpl_send_flags;    /*!< send flags for replies */
281 	struct msg_start first_line;   /*!< Message first line */
282 	struct via_body* via1;         /*!< The first via */
283 	struct via_body* via2;         /*!< The second via */
284 	struct hdr_field* headers;     /*!< All the parsed headers*/
285 	struct hdr_field* last_header; /*!< Pointer to the last parsed header*/
286 	hdr_flags_t parsed_flag;    /*!< Already parsed header field types */
287 
288 	/* Via, To, CSeq, Call-Id, From, end of header*/
289 	/* pointers to the first occurrences of these headers;
290 	 * everything is also saved in 'headers'
291 	 * (WARNING: do not deallocate them twice!)*/
292 
293 	struct hdr_field* h_via1;
294 	struct hdr_field* h_via2;
295 	struct hdr_field* callid;
296 	struct hdr_field* to;
297 	struct hdr_field* cseq;
298 	struct hdr_field* from;
299 	struct hdr_field* contact;
300 	struct hdr_field* maxforwards;
301 	struct hdr_field* route;
302 	struct hdr_field* record_route;
303 	struct hdr_field* content_type;
304 	struct hdr_field* content_length;
305 	struct hdr_field* authorization;
306 	struct hdr_field* expires;
307 	struct hdr_field* proxy_auth;
308 	struct hdr_field* supported;
309 	struct hdr_field* require;
310 	struct hdr_field* proxy_require;
311 	struct hdr_field* unsupported;
312 	struct hdr_field* allow;
313 	struct hdr_field* event;
314 	struct hdr_field* accept;
315 	struct hdr_field* accept_language;
316 	struct hdr_field* organization;
317 	struct hdr_field* priority;
318 	struct hdr_field* subject;
319 	struct hdr_field* user_agent;
320 	struct hdr_field* server;
321 	struct hdr_field* content_disposition;
322 	struct hdr_field* diversion;
323 	struct hdr_field* rpid;
324 	struct hdr_field* refer_to;
325 	struct hdr_field* session_expires;
326 	struct hdr_field* min_se;
327 	struct hdr_field* sipifmatch;
328 	struct hdr_field* subscription_state;
329 	struct hdr_field* date;
330 	struct hdr_field* identity;
331 	struct hdr_field* identity_info;
332 	struct hdr_field* pai;
333 	struct hdr_field* ppi;
334 	struct hdr_field* path;
335 	struct hdr_field* privacy;
336 	struct hdr_field* min_expires;
337 
338 	struct msg_body* body;
339 
340 	char* eoh;        /*!< pointer to the end of header (if found) or null */
341 	char* unparsed;   /*!< here we stopped parsing*/
342 
343 	struct receive_info rcv; /*!< source & dest ip, ports, proto a.s.o*/
344 
345 	char* buf;        /*!< scratch pad, holds a modified message,
346 						*  via, etc. point into it */
347 	unsigned int len; /*!< message len (orig) */
348 
349 	/* modifications */
350 
351 	str new_uri; /*!< changed first line uri, when you change this
352 					don't forget to set parsed_uri_ok to 0*/
353 
354 	str dst_uri; /*!< Destination URI, must be forwarded to this URI if len != 0 */
355 
356 	/* current uri */
357 	int parsed_uri_ok; /*!< 1 if parsed_uri is valid, 0 if not, set if to 0
358 						if you modify the uri (e.g change new_uri)*/
359 	struct sip_uri parsed_uri; /*!< speed-up > keep here the parsed uri*/
360 	int parsed_orig_ruri_ok; /*!< 1 if parsed_orig_uri is valid, 0 if not, set if to 0
361 								if you modify the uri (e.g change new_uri)*/
362 	struct sip_uri parsed_orig_ruri; /*!< speed-up > keep here the parsed orig uri*/
363 
364 	struct lump* add_rm;       /*!< used for all the forwarded requests/replies */
365 	struct lump* body_lumps;     /*!< Lumps that update Content-Length */
366 	struct lump_rpl *reply_lump; /*!< only for localy generated replies !!!*/
367 
368 	/*! \brief str add_to_branch;
369 		whatever whoever want to append to Via branch comes here */
370 	char add_to_branch_s[MAX_BRANCH_PARAM_LEN];
371 	int add_to_branch_len;
372 
373 	unsigned int  hash_index; /*!< index to TM hash table; stored in core
374 								to avoid unnecessary calculations */
375 	unsigned int msg_flags; /*!< internal flags used by core */
376 	flag_t flags; /*!< config flags */
377 	flag_t xflags[KSR_XFLAGS_SIZE]; /*!< config extended flags */
378 	str set_global_address;
379 	str set_global_port;
380 	struct socket_info* force_send_socket; /*!< force sending on this socket */
381 	str path_vec;
382 	str instance;
383 	unsigned int reg_id;
384 	str ruid;
385 	str location_ua;
386 	int otcpid; /*!< outbound tcp connection id, if known */
387 
388 	/* structure with fields that are needed for local processing
389 	 * - not cloned to shm, reset to 0 in the clone */
390 	msg_ldata_t ldv;
391 
392 	/* IMPORTANT: when adding new fields in this structure (sip_msg_t),
393 	 * be sure it is freed in free_sip_msg() and it is cloned or reset
394 	 * to shm structure for transaction - see sip_msg_clone.c. In tm
395 	 * module, take care of these fields for faked environemt used for
396 	 * runing failure handlers - see modules/tm/t_reply.c */
397 } sip_msg_t;
398 
399 /*! \brief pointer to a fakes message which was never received ;
400 	(when this message is "relayed", it is generated out
401 	of the original request)
402 */
403 #define FAKED_REPLY     ((struct sip_msg *) -1)
404 
405 extern int via_cnt;
406 /** global  request flags.
407  *  msg->msg_flags should be OR'ed with it before
408  * a flag value is checked, e.g.:
409  * if ((msg->msg_flags|global_req_flags) & FL_XXX) ...
410  */
411 extern unsigned int global_req_flags;
412 
413 
414 int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg);
415 
416 int parse_headers(struct sip_msg* const msg, const hdr_flags_t flags, const int next);
417 
418 char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hdr);
419 
420 void free_sip_msg(struct sip_msg* const msg);
421 
422 /*! \brief make sure all HFs needed for transaction identification have been
423 	parsed; return 0 if those HFs can't be found
424 */
425 int check_transaction_quadruple(sip_msg_t* const msg);
426 
427 /*! \brief returns a pointer to the begining of the msg's body
428  */
429 char* get_body(sip_msg_t* const msg);
430 
431 /*! \brief If the new_uri is set, then reset it */
432 void reset_new_uri(struct sip_msg* const msg);
433 
434 /*! \brief
435  * Make a private copy of the string and assign it to dst_uri
436  */
437 int set_dst_uri(struct sip_msg* const msg, const str* const uri);
438 
439 /*! \brief If the dst_uri is set to an URI then reset it */
440 void reset_dst_uri(struct sip_msg* const msg);
441 
442 hdr_field_t* get_hdr(const sip_msg_t* const msg, const enum _hdr_types_t ht);
443 hdr_field_t* next_sibling_hdr(const hdr_field_t* const hf);
444 /** not used yet */
445 hdr_field_t* get_hdr_by_name(const sip_msg_t* const msg, const char* const name,
446 		const int name_len);
447 hdr_field_t* next_sibling_hdr_by_name(const hdr_field_t* const hf);
448 
449 int set_path_vector(struct sip_msg* msg, str* path);
450 
451 void reset_path_vector(struct sip_msg* const msg);
452 
453 int set_instance(struct sip_msg* msg, str* instance);
454 
455 void reset_instance(struct sip_msg* const msg);
456 
457 int set_ruid(struct sip_msg* msg, str* ruid);
458 
459 void reset_ruid(struct sip_msg* const msg);
460 
461 int set_ua(struct sip_msg* msg, str *location_ua);
462 
463 void reset_ua(struct sip_msg* const msg);
464 
465 /** force a specific send socket for forwarding a request.
466  * @param msg - sip msg.
467  * @param fsocket - forced socket, pointer to struct socket_info, can be 0 (in
468  *                  which case it's equivalent to reset_force_socket()).
469  */
470 #define set_force_socket(msg, fsocket) \
471 	do { \
472 		(msg)->force_send_socket=(fsocket); \
473 		if ((msg)->force_send_socket) \
474 			(msg)->fwd_send_flags.f |= SND_F_FORCE_SOCKET; \
475 		else \
476 			(msg)->fwd_send_flags.f &= ~SND_F_FORCE_SOCKET; \
477 	} while (0)
478 
479 /** reset a previously forced send socket. */
480 #define reset_force_socket(msg) set_force_socket(msg, 0)
481 
482 /**
483  * struct to identify a msg context
484  * - the pair of message-id and pid (fields in sip_msg_t)
485  */
486 typedef struct msg_ctx_id {
487 	unsigned int msgid;
488 	int pid;
489 } msg_ctx_id_t;
490 
491 /**
492  * set msg context id
493  * - return: -1 on error; 0 - on set
494  */
495 int msg_ctx_id_set(const sip_msg_t* const msg, msg_ctx_id_t* const mid);
496 
497 /**
498  * check msg context id
499  * - return: -1 on error; 0 - on no match; 1 - on match
500  */
501 int msg_ctx_id_match(const sip_msg_t* const msg, const msg_ctx_id_t* const mid);
502 
503 /**
504  * set msg time value
505  */
506 int msg_set_time(sip_msg_t* const msg);
507 
508 /**
509  * reset content of msg->ldv (msg_ldata_t structure)
510  */
511 void msg_ldata_reset(sip_msg_t*);
512 
513 /**
514  * get source ip, port and protocol in SIP URI format
515  */
516 int get_src_uri(sip_msg_t *m, int tmode, str *uri);
517 
518 /**
519  * get source proto:ip:port (socket address format)
520  */
521 int get_src_address_socket(sip_msg_t *m, str *ssock);
522 
523 /**
524  * get received-on-socket ip, port and protocol in SIP URI format
525  */
526 int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype);
527 
528 #endif
529