Modifying the return value of cfg_set* functions, in order to make
[sip-router] / ser_stun.c
1 /*
2  * $Id$
3  *
4  * Copyright (C) 2001-2003 FhG Fokus
5  *
6  * This file is part of ser, a free SIP server.
7  *
8  * ser is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  *
13  * For a license to use the ser software under conditions
14  * other than those described here, or to purchase support for this
15  * software, please contact iptel.org by e-mail at the following addresses:
16  *    info@iptel.org
17  *
18  * ser is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License 
24  * along with this program; if not, write to the Free Software 
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  *
27  * History
28  * --------
29  *  2006-10-13  created (vlada)
30  *  2006-12-14  fixed calculation of body length (vlada) 
31  */
32
33 #ifdef USE_STUN 
34  
35 #include <arpa/inet.h>
36 #include <openssl/sha.h>
37 #include "ser_stun.h"
38 #include "forward.h"
39
40 /*
41  * ****************************************************************************
42  *                     Declaration of functions                               *
43  * ****************************************************************************
44  */
45 int stun_parse_header(struct stun_msg* req, USHORT_T* error_code);
46 int stun_parse_body(
47                                 struct stun_msg* req,
48                                 struct stun_unknown_att** unknown,
49                                 USHORT_T* error_code);
50 void stun_delete_unknown_attrs(struct stun_unknown_att* unknown);
51 struct stun_unknown_att* stun_alloc_unknown_attr(USHORT_T type);
52 int stun_add_address_attr(struct stun_msg* res, 
53                                                 UINT_T          af,
54                                                 USHORT_T        port,
55                                                 UINT_T*         ip_addr,
56                                                 USHORT_T        type,
57                                                 int do_xor);
58 int add_unknown_attr(struct stun_msg* res, struct stun_unknown_att* unknown);
59 int add_error_code(struct stun_msg* res, USHORT_T error_code);
60 int add_fingerprint(struct stun_buffer* msg);
61 int copy_str_to_buffer(struct stun_msg* res, const char* data, UINT_T pad);
62 int validate_fingerprint(struct stun_msg* req, USHORT_T* error_code);
63 int reallock_buffer(struct stun_buffer* buffer, UINT_T len);
64 int buf_copy(struct stun_buffer* msg, void* source, UINT_T len);
65 void clean_memory(struct stun_msg* req,
66                                 struct stun_msg* res,   struct stun_unknown_att* unknown);
67 int stun_create_response(
68                                                 struct stun_msg* req,
69                                                 struct stun_msg* res,
70                                                 struct receive_info* ri,
71                                                 struct stun_unknown_att* unknown, 
72                                                 UINT_T error_code);
73 int stun_add_common_integer_attr(struct stun_msg* res, USHORT_T type, UINT_T value);
74 int stun_add_common_text_attr(struct stun_msg* res, USHORT_T type, char* value, 
75                                                         USHORT_T pad);
76
77
78 /*
79  * ****************************************************************************
80  *                      Definition of functions                               *
81  * ****************************************************************************
82  */
83  
84 /* 
85  * stun_process_msg(): 
86  *                      buf - incoming message
87  *                      len - length of incoming message
88  *                      ri  - information about socket that received a message and 
89  *                also information about sender (its IP, port, protocol)
90  * 
91  * This function ensures processing of incoming message. It's common for both
92  * TCP and UDP protocol. There is no other function as an interface.
93  * 
94  * Return value:        0       if there is no environment error
95  *                                      -1      if there is some enviroment error such as insufficiency
96  *                                              of memory
97  * 
98  */
99 int stun_process_msg(char* buf, unsigned len, struct receive_info* ri)
100 {
101         struct stun_msg                         msg_req;
102         struct stun_msg                         msg_res;
103         struct dest_info                        dst;
104         struct stun_unknown_att*        unknown;
105         USHORT_T                                        error_code;
106          
107         memset(&msg_req, 0, sizeof(msg_req));
108         memset(&msg_res, 0, sizeof(msg_res));
109         
110         msg_req.msg.buf.s = buf;
111         msg_req.msg.buf.len = len;      
112         unknown = NULL;
113         error_code = RESPONSE_OK;
114         
115         if (stun_parse_header(&msg_req, &error_code) != 0) {
116                 goto error;
117         }
118         
119         if (error_code == RESPONSE_OK) {
120                 if (stun_parse_body(&msg_req, &unknown, &error_code) != 0) {
121                         goto error;
122                 }
123         }
124         
125         if (stun_create_response(&msg_req, &msg_res, ri,  
126                                                         unknown, error_code) != 0) {
127                 goto error;
128         }
129         
130         init_dst_from_rcv(&dst, ri);
131
132 #ifdef EXTRA_DEBUG      
133         struct ip_addr ip;
134         su2ip_addr(&ip, &dst.to);
135         LOG(L_DBG, "DEBUG: stun_process_msg: decoded request from (%s:%d)\n", ip_addr2a(&ip), 
136                 su_getport(&dst.to));
137 #endif
138         
139         /* send STUN response */
140         if (msg_send(&dst, msg_res.msg.buf.s, msg_res.msg.buf.len) != 0) {
141                 goto error;
142         }
143         
144 #ifdef EXTRA_DEBUG
145         LOG(L_DBG, "DEBUG: stun_process_msg: send response\n");
146 #endif
147         clean_memory(&msg_req, &msg_res, unknown);
148         return 0;
149         
150 error:
151 #ifdef EXTRA_DEBUG
152         LOG(L_DBG, "DEBUG: stun_process_msg: failed to decode request\n");
153 #endif
154         clean_memory(&msg_req, &msg_res, unknown);
155         return FATAL_ERROR;
156 }
157
158 /*
159  * stun_parse_header():
160  *                      - req: request from host that should be processed
161  *                      - error_code: indication of any protocol error
162  * 
163  * This function ensures parsing of incoming header.
164  * 
165  * Return value:        0       if there is no environment error
166  *                                      -1      if there is some enviroment error such as insufficiency
167  *                                              of memory
168  */
169
170 int stun_parse_header(struct stun_msg* req, USHORT_T* error_code)
171 {
172         
173         if (sizeof(req->hdr) > req->msg.buf.len) {
174                 /* the received message does not contain whole header */
175                 LOG(L_INFO, "INFO: stun_parse_header: incomplete header of STUN message\n");
176                 /* Any better solution? IMHO it's not possible to send error response
177                  * because the transaction ID is not available.
178                  */
179                 return FATAL_ERROR;
180         }
181         
182         memcpy(&req->hdr, req->msg.buf.s, sizeof(struct stun_hdr));
183         req->hdr.type = ntohs(req->hdr.type);
184         
185         /* the SER supports only Binding Request right now */ 
186         if (req->hdr.type != BINDING_REQUEST) {
187                 LOG(L_INFO, "INFO: stun_parse_header: unsupported type of STUN message: %x\n", 
188                                         req->hdr.type);
189                 /* resending of same message is not welcome */
190                 *error_code = GLOBAL_FAILURE_ERR;
191         }
192         
193         req->hdr.len = ntohs(req->hdr.len);
194         
195         /* check if there is correct magic cookie */
196         req->old = (req->hdr.id.magic_cookie == htonl(MAGIC_COOKIE)) ? 0 : 1;
197
198 #ifdef EXTRA_DEBUG
199         LOG(L_DBG, "DEBUG: stun_parse_header: request is old: %i\n", req->old);
200 #endif
201         return 0;
202 }
203
204 /*
205  * stun_parse_body():
206  *                      - req: request from host that should be processed
207  *                      - unknown: this is a link list header of attributes 
208  *                                         that are unknown to SER; defaul value is NULL
209  *                      - error_code: indication of any protocol error
210  * 
211  * Return value:        0       if there is no environment error
212  *                                      -1      if there is some enviroment error such as insufficiency
213  *                                              of memory
214  */
215 int stun_parse_body(
216                                 struct stun_msg* req,
217                                 struct stun_unknown_att** unknown,
218                                 USHORT_T* error_code)
219 {
220         UINT_T not_parsed;
221         struct stun_attr attr;
222         USHORT_T attr_size;
223         UINT_T padded_len;
224         struct stun_unknown_att*        tmp_unknown;
225         struct stun_unknown_att*        body;
226         char*   buf;
227         int             fp_present;
228         
229         attr_size = sizeof(struct stun_attr);
230         buf = &req->msg.buf.s[sizeof(struct stun_hdr)];
231         fp_present = 0;
232         
233         /* 
234          * Mark the body lenght as unparsed.
235          */
236         not_parsed = req->msg.buf.len - sizeof(struct stun_hdr);
237         
238         if (not_parsed != req->hdr.len) {
239 #ifdef EXTRA_DEBUG
240                 LOG(L_DBG, "DEBUG: stun_parse_body: body too short to be valid\n");
241 #endif
242                 *error_code = BAD_REQUEST_ERR;
243                 return 0; 
244         }
245         
246         tmp_unknown = *unknown;
247         body = NULL;
248         
249         while (not_parsed > 0 && *error_code == RESPONSE_OK) {
250                 memset(&attr, 0, attr_size);
251                 
252                 /* check if there are 4 bytes for attribute type and its value */
253                 if (not_parsed < 4) {
254 #ifdef EXTRA_DEBUG
255                         LOG(L_DBG, "DEBUG: stun_parse_body: attribute header short to be valid\n");
256 #endif
257                         *error_code = BAD_REQUEST_ERR;
258                         continue;
259                 }
260                 
261                 memcpy(&attr, buf, attr_size);
262                 
263                 buf += attr_size;
264                 not_parsed -= attr_size;
265                 
266                 /* check if there is enought unparsed space for attribute's value */
267                 if (not_parsed < ntohs(attr.len)) {
268 #ifdef EXTRA_DEBUG
269                         LOG(L_DBG, "DEBUG: stun_parse_body: remaining message is shorter then attribute length\n");
270 #endif
271                         *error_code = BAD_REQUEST_ERR;
272                         continue;
273                 }
274                 
275                 /* check if the attribute is known to the server */
276                 switch (ntohs(attr.type)) {                     
277                         case REALM_ATTR:
278                         case NONCE_ATTR:
279                         case MAPPED_ADDRESS_ATTR:
280                         case XOR_MAPPED_ADDRESS_ATTR:
281                         case ALTERNATE_SERVER_ATTR:
282                         case REFRESH_INTERVAL_ATTR:
283                         case RESPONSE_ADDRESS_ATTR:
284                         case SOURCE_ADDRESS_ATTR:
285                         case REFLECTED_FROM_ATTR:               
286                         case CHANGE_REQUEST_ATTR:
287                         case CHANGED_ADDRESS_ATTR:
288                                 padded_len = ntohs(attr.len);
289 #ifdef EXTRA_DEBUG
290                                 LOG(L_DBG, "DEBUG: stun_parse_body: known attributes\n");
291 #endif
292                                 break;
293                         
294                         /* following attributes must be padded to 4 bytes */
295                         case USERNAME_ATTR:
296                         case PASSWORD_ATTR:
297                         case ERROR_CODE_ATTR:
298                         case UNKNOWN_ATTRIBUTES_ATTR:
299                         case SERVER_ATTR:
300                                 padded_len = PADDED_TO_FOUR(ntohs(attr.len));
301 #ifdef EXTRA_DEBUG
302                                 LOG(L_DBG, "DEBUG: stun_parse_body: padded to four\n");
303 #endif
304                                 break;
305
306                         /* MESSAGE_INTEGRITY must be padded to sixty four bytes*/
307                         case MESSAGE_INTEGRITY_ATTR:
308 #ifdef EXTRA_DEBUG
309                                 LOG(L_DBG, "DEBUG: stun_parse_body: message integrity attribute found\n");
310 #endif
311                                 padded_len = PADDED_TO_SIXTYFOUR(ntohs(attr.len));
312                                 break;
313                         
314                         case FINGERPRINT_ATTR:
315 #ifdef EXTRA_DEBUG
316                                 LOG(L_DBG, "DEBUG: stun_parse_body: fingerprint attribute found\n");
317 #endif
318                                 fp_present = 1;
319                                 if (ntohs(attr.len) != SHA_DIGEST_LENGTH) {
320                                         LOG(L_WARN, 
321                                                 "WARNING: STUN: Incorrect fingerprint of request.\n");
322                                         *error_code = BAD_REQUEST_ERR;
323                                         continue;
324                                 }
325
326                                 memcpy(req->fp, buf, SHA_DIGEST_LENGTH);
327                                 if(stun_allow_fp) {
328                                         if (validate_fingerprint(req, error_code) != 0) {
329                                                 LOG(L_WARN, 
330                                                         "WARNING: STUN: Incorrect fingerprint of request.\n");
331                                                 *error_code = BAD_REQUEST_ERR;
332                                                 continue;
333                                         }
334                                 } 
335
336                                 padded_len = SHA_DIGEST_LENGTH;
337                                 if (not_parsed > SHA_DIGEST_LENGTH) {
338 #ifdef EXTRA_DEBUG
339                                         LOG(L_DBG, "DEBUG: stun_parse_body: fingerprint is not the last attribute\n");
340 #endif
341                                         /* fingerprint must be last parameter in request */
342                                         *error_code = BAD_REQUEST_ERR;
343                                         continue;
344                                 }
345                                 break;
346                         
347                         default:
348                                 /* 
349                                  * the attribute is uknnown to the server
350                                  * let see if it's necessary to generate error response 
351                                  */
352 #ifdef EXTRA_DEBUG
353                                 LOG(L_DBG, "DEBUG: low endian: attr - 0x%x   const - 0x%x\n", ntohs(attr.type), MANDATORY_ATTR);
354                     LOG(L_DBG, "DEBUG: big endian: attr - 0x%x   const - 0x%x\n", attr.type, htons(MANDATORY_ATTR));
355 #endif
356                                 if (ntohs(attr.type) <= MANDATORY_ATTR) {
357 #ifdef EXTRA_DEBUG
358                                 LOG(L_DBG, "DEBUG: stun_parse_body: mandatory unknown attribute found - 0x%x\n", ntohs(attr.type));
359 #endif          
360                                         tmp_unknown = stun_alloc_unknown_attr(attr.type);
361                                         if (tmp_unknown == NULL) {
362                                                 return FATAL_ERROR;
363                                         }
364                                         if (*unknown == NULL) {
365                                                 *unknown = body = tmp_unknown;
366                                         }
367                                         else { 
368                                                 body->next = tmp_unknown;
369                                                 body = body->next;
370                                         }
371                                 }
372 #ifdef EXTRA_DEBUG
373         else {
374                                   LOG(L_DBG, "DEBUG: stun_parse_body: optional unknown attribute found - 0x%x\n", ntohs(attr.type));
375         }
376 #endif
377                                 padded_len = ntohs(attr.len);
378                                 break;
379                 }
380                 buf += padded_len;
381                 not_parsed -= padded_len;
382         }  /* while */
383         
384         /*
385          * The unknown attribute error code must set after parsing of whole body
386          * because it's necessary to obtain all of unknown attributes! 
387          */
388         if (*error_code == RESPONSE_OK && *unknown != NULL) {
389                 *error_code = UNKNOWN_ATTRIBUTE_ERR;
390         } 
391         
392         if (fp_present == 0 && req->old == 0) {
393 #ifdef EXTRA_DEBUG
394                 LOG(L_DBG, "DEBUG: stun_parse_body: fingerprint is missing is this new request\n");
395 #endif
396                 /* missing mandatory attribute fingerprint */
397                 *error_code = BAD_REQUEST_ERR;
398         }
399         
400         return 0;
401 }
402
403 /*
404  * stun_create_response():
405  *                      - req: original request from host
406  *                      - res: this will represent response to host
407  *                      - ri: information about request, necessary because of IP 
408  *                                address and port 
409  *                      - unknown: link list of unknown attributes
410  *                      - error_code: indication of any protocol error
411  * 
412  * The function stun_create_response ensures creating response to a host.
413  * The type of response depends on value of error_code parameter.
414  * 
415  * Return value:        0       if there is no environment error
416  *                                      -1      if there is some enviroment error such as insufficiency
417  *                                              of memory  
418  */
419
420 int stun_create_response(
421                                                 struct stun_msg* req,
422                                                 struct stun_msg* res,
423                                                 struct receive_info* ri,
424                                                 struct stun_unknown_att* unknown, 
425                                                 UINT_T error_code)
426 {
427         UINT_T msg_len;
428         /*
429          * Alloc some space for response.
430          * Optimalization? - maybe it would be better to use biggish static array.
431          */
432         res->msg.buf.s = (char *) pkg_malloc(sizeof(char)*STUN_MSG_LEN);
433         if (res->msg.buf.s == NULL) {
434                 LOG(L_ERR, "ERROR: STUN: out of memory\n");
435                 return FATAL_ERROR;
436         }
437         
438         memset(res->msg.buf.s, 0, sizeof(char)*STUN_MSG_LEN); 
439         res->msg.buf.len = 0;
440         res->msg.empty = STUN_MSG_LEN;
441         
442         /* use magic cookie and transaction ID from request */
443         memcpy(&res->hdr.id, &req->hdr.id, sizeof(struct transaction_id));
444         /* the correct body length will be added ASAP it will be known */ 
445         res->hdr.len = htons(0);
446         
447         if (error_code == RESPONSE_OK) {
448 #ifdef EXTRA_DEBUG
449                 LOG(L_DBG, "DEBUG: stun_create_response: creating normal response\n");
450 #endif
451                 res->hdr.type = htons(BINDING_RESPONSE);
452                 
453                 /* copy header into msg buffer */
454                 if (buf_copy(&res->msg, (void *) &res->hdr, 
455                                         sizeof(struct stun_hdr)) != 0) {
456 #ifdef EXTRA_DEBUG
457                         LOG(L_DBG, "DEBUG: stun_create_response: failed to copy buffer\n");
458 #endif
459                         return FATAL_ERROR;
460                 }
461
462                 /* 
463                  * If the SER received message in old format, then the body will 
464                  * contain MAPPED-ADDRESS attribute instead of XOR-MAPPED-ADDRESS
465                  * attribute.
466                  */             
467                 if (req->old == 0) {
468                         if (stun_add_address_attr(res, ri->src_ip.af, ri->src_port, 
469                                                   ri->src_ip.u.addr32, XOR_MAPPED_ADDRESS_ATTR, 
470                                                   XOR) != 0) {
471 #ifdef EXTRA_DEBUG
472                                 LOG(L_DBG, "DEBUG: stun_create_response: failed to add address\n");
473 #endif
474                                 return FATAL_ERROR;
475                         }
476                         
477                         if (stun_add_common_integer_attr(res, REFRESH_INTERVAL_ATTR, 
478                                                 stun_refresh_interval) != 0) {
479 #ifdef EXTRA_DEBUG
480                                 LOG(L_DBG, "DEBUG: stun_create_response: failed to common attributes\n");
481 #endif
482                                 return FATAL_ERROR;
483                         }
484                 }
485                 else {
486                         if (stun_add_address_attr(res, ri->src_ip.af, ri->src_port, 
487                                                 ri->src_ip.u.addr32, MAPPED_ADDRESS_ATTR, !XOR) != 0) {
488 #ifdef EXTRA_DEBUG
489                                 LOG(L_DBG, "DEBUG: stun_create_response: failed to add address\n");
490 #endif
491                                 return FATAL_ERROR;
492                         }
493                 }
494         }
495         else {
496 #ifdef EXTRA_DEBUG
497                 LOG(L_DBG, "DEBUG: stun_create_response: creating error response\n");
498 #endif
499                 res->hdr.type = htons(BINDING_ERROR_RESPONSE);
500                 
501                 if (buf_copy(&res->msg, (void *) &res->hdr, 
502                                                                 sizeof(struct stun_hdr)) != 0) {
503 #ifdef EXTRA_DEBUG
504                         LOG(L_DBG, "DEBUG: stun_create_response: failed to copy buffer\n");
505 #endif
506                         return FATAL_ERROR;
507                 }
508                 
509                 if (add_error_code(res, error_code) != 0) {
510 #ifdef EXTRA_DEBUG
511                         LOG(L_DBG, "DEBUG: stun_create_response: failed to add error code\n");
512 #endif
513                         return FATAL_ERROR;
514                 }
515                 
516                 if (unknown != NULL) {
517                         if (add_unknown_attr(res, unknown) != 0) {
518 #ifdef EXTRA_DEBUG
519                                 LOG(L_DBG, "DEBUG: stun_create_response: failed to add unknown attribute\n");
520 #endif
521                                 return FATAL_ERROR;
522                         }
523                 } 
524         }
525         
526         if (req->old == 0) {
527                 /* 
528                  * add optional information about server; attribute SERVER is not a part of 
529                  * rfc3489.txt 
530                  * */
531                 if (stun_add_common_text_attr(res, SERVER_ATTR, SERVER_HDR, PAD4)!=0) {
532 #ifdef EXTRA_DEBUG
533                         LOG(L_DBG, "DEBUG: stun_create_response: failed to add common text attribute\n");
534 #endif
535                         return FATAL_ERROR;
536                 }
537         }       
538         
539         if (req->old == 0 && stun_allow_fp) {
540                 /* count length of body except header and fingerprint
541                  * and copy message length at the beginning of buffer
542            */
543           msg_len = res->msg.buf.len - sizeof(struct stun_hdr);
544           msg_len += SHA_DIGEST_LENGTH + sizeof(struct stun_attr);
545                 res->hdr.len = htons(msg_len);
546                 memcpy(&res->msg.buf.s[sizeof(USHORT_T)], (void *) &res->hdr.len,
547                 sizeof(USHORT_T));
548                         
549                 if (add_fingerprint(&res->msg) != 0) {
550 #ifdef EXTRA_DEBUG
551                         LOG(L_DBG, "DEBUG: stun_create_response: failed to add fingerprint\n");
552 #endif
553                         return FATAL_ERROR;
554                 }
555         }
556         else {
557                 res->hdr.len = htons(res->msg.buf.len - sizeof(struct stun_hdr));
558                 memcpy(&res->msg.buf.s[sizeof(USHORT_T)], (void *) &res->hdr.len,
559                 sizeof(USHORT_T));
560         }
561         
562         return 0;
563 }
564
565 /*
566  * add_unknown_attr()
567  *                      - res: response representation
568  *                      - unknown: link list of unknown attributes
569  * 
570  * The function add_unknown_attr ensures copy of link list of unknown 
571  * attributes into response buffer.
572  * 
573  * Return value:        0       if there is no environment error
574  *                                      -1      if there is some enviroment error such as insufficiency
575  *                                              of memory
576  * 
577  */
578 int add_unknown_attr(struct stun_msg* res, struct stun_unknown_att* unknown)
579 {
580         struct stun_attr attr;
581         struct stun_unknown_att* tmp_unknown;
582         UINT_T          counter;
583         USHORT_T        orig_len;
584
585         counter = 0;
586         orig_len = res->msg.buf.len;
587         tmp_unknown = unknown;
588         
589         attr.type = htons(UNKNOWN_ATTRIBUTES_ATTR);
590         attr.len = htons(0);
591         
592         if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
593 #ifdef EXTRA_DEBUG
594                 LOG(L_DBG, "DEBUG: add_unknown_attr: failed to copy buffer\n");
595 #endif
596                 return FATAL_ERROR;
597         }
598         
599         while (tmp_unknown != NULL) {
600                 if (buf_copy(&res->msg, (void *)&tmp_unknown->type, 
601                                                                 sizeof(USHORT_T)) != 0) {
602 #ifdef EXTRA_DEBUG
603                         LOG(L_DBG, "DEBUG: add_unknown_attr: failed to copy unknown attribute\n");
604 #endif
605                         return FATAL_ERROR;
606                 }
607                 tmp_unknown = tmp_unknown->next;
608                 ++counter;
609         }
610         
611         attr.len = htons(res->msg.buf.len - orig_len);
612         memcpy(&res->msg.buf.s[orig_len], (void *)&attr, sizeof(struct stun_attr));
613         
614         /* check if there is an odd number of unknown attributes and if yes, 
615          * repeat one of them because of padding to 32
616          */
617         if (counter/2 != 0 && unknown != NULL) {
618                 if (buf_copy(&res->msg, (void *)&unknown->type, sizeof(USHORT_T))!=0) {
619 #ifdef EXTRA_DEBUG
620                         LOG(L_DBG, "DEBUG: add_unknown_attr: failed to padd\n");
621 #endif
622                         return FATAL_ERROR;
623                 }
624         }       
625         
626         return 0;
627 }
628
629 /*
630  * add_error_code()
631  *                      - res: response representation
632  *                      - error_code: value of error type
633  * 
634  * The function add_error_code ensures copy of link list of unknown 
635  * attributes into response buffer.
636  * 
637  * Return value:        0       if there is no environment error
638  *                                      -1      if there is some enviroment error such as insufficiency
639  *                                              of memory
640  */
641 int add_error_code(struct stun_msg* res, USHORT_T error_code)
642 {
643         struct stun_attr attr;
644         USHORT_T        orig_len;
645         USHORT_T        two_bytes;
646         int                     text_pad;
647         char            err[2];
648         
649         orig_len = res->msg.buf.len;
650         text_pad = 0;
651         
652         /* the type and length will be copy as last one because of unknown length*/
653         if (res->msg.buf.len < sizeof(struct stun_attr)) {
654                 if (reallock_buffer(&res->msg, sizeof(struct stun_attr)) != 0) {
655 #ifdef EXTRA_DEBUG
656                         LOG(L_DBG, "DEBUG: add_error_code: failed to reallocate buffer\n");
657 #endif
658                         return FATAL_ERROR;
659                 }
660         }
661         res->msg.buf.len += sizeof(struct stun_attr);
662         res->msg.empty -= sizeof(struct stun_attr);
663         
664         /* first two bytes are empty */
665         two_bytes = 0x0000;
666         
667         if (buf_copy(&res->msg, (void *) &two_bytes, sizeof(USHORT_T)) != 0) {
668 #ifdef EXTRA_DEBUG
669                 LOG(L_DBG, "DEBUG: add_error_code: failed to copy buffer\n");
670 #endif
671                 return FATAL_ERROR;
672         }
673         
674         err[0] = error_code / 100;
675         err[1] = error_code % 100;
676         if (buf_copy(&res->msg, (void *) err, sizeof(UCHAR_T)*2) != 0) {
677                 return FATAL_ERROR;
678         }
679         
680         switch (error_code) {
681                 case TRY_ALTERNATE_ERR:
682                         text_pad = copy_str_to_buffer(res, TRY_ALTERNATE_TXT, PAD4); 
683                         break;
684                 case BAD_REQUEST_ERR:
685                         text_pad = copy_str_to_buffer(res, BAD_REQUEST_TXT, PAD4); 
686                         break;
687                 case UNAUTHORIZED_ERR:
688                         text_pad = copy_str_to_buffer(res, UNAUTHORIZED_TXT, PAD4); 
689                         break;
690                 case UNKNOWN_ATTRIBUTE_ERR:
691                         text_pad = copy_str_to_buffer(res, UNKNOWN_ATTRIBUTE_TXT, PAD4);
692                         break;
693                 case STALE_CREDENTIALS_ERR:
694                         text_pad = copy_str_to_buffer(res, STALE_CREDENTIALS_TXT, PAD4); 
695                         break;
696                 case INTEGRITY_CHECK_ERR:
697                         text_pad = copy_str_to_buffer(res, INTEGRITY_CHECK_TXT, PAD4); 
698                         break;
699                 case MISSING_USERNAME_ERR:
700                         text_pad = copy_str_to_buffer(res, MISSING_USERNAME_TXT, PAD4); 
701                         break;
702                 case USE_TLS_ERR:
703                         text_pad = copy_str_to_buffer(res, USE_TLS_TXT, PAD4); 
704                         break;
705                 case MISSING_REALM_ERR:
706                         text_pad = copy_str_to_buffer(res, MISSING_REALM_TXT, PAD4); 
707                         break;
708                 case MISSING_NONCE_ERR:
709                         text_pad = copy_str_to_buffer(res, MISSING_NONCE_TXT, PAD4); 
710                         break;
711                 case UNKNOWN_USERNAME_ERR:
712                         text_pad = copy_str_to_buffer(res, UNKNOWN_USERNAME_TXT, PAD4); 
713                         break;
714                 case STALE_NONCE_ERR:
715                         text_pad = copy_str_to_buffer(res, STALE_NONCE_TXT, PAD4);
716                         break;
717                 case SERVER_ERROR_ERR:
718                         text_pad = copy_str_to_buffer(res, SERVER_ERROR_TXT, PAD4); 
719                         break;
720                 case GLOBAL_FAILURE_ERR:
721                         text_pad = copy_str_to_buffer(res, GLOBAL_FAILURE_TXT, PAD4); 
722                         break;
723                 default:
724                         LOG(L_ERR, "ERROR: STUN: Unknown error code.\n");
725                         break;
726         }
727         if (text_pad < 0) {
728 #ifdef EXTRA_DEBUG
729                 LOG(L_DBG, "DEBUG: add_error_code: text_pad is negative\n");
730 #endif
731                 goto error;
732         }
733         attr.type = htons(ERROR_CODE_ATTR);
734         /* count length of "value" field -> without type and lehgth field */
735         attr.len = htons(res->msg.buf.len - orig_len - 
736                                          text_pad - sizeof(struct stun_attr));
737         memcpy(&res->msg.buf.s[orig_len], (void *)&attr, sizeof(struct stun_attr));
738         
739         return 0;
740
741 error:
742         return FATAL_ERROR;
743 }
744
745 /*
746  * copy_str_to_buffer()
747  *                      - res: response representation
748  *                      - data: text data, in our case almost text representation of error
749  *                      - pad: the size of pad (for how much bytes the string should be 
750  *                                 padded
751  * 
752  * The function copy_str_to_buffer ensures copy of text buffer into response
753  * buffer.
754  * 
755  * Return value:        0       if there is no environment error
756  *                                      -1      if there is some enviroment error such as insufficiency
757  *                                              of memory
758  */
759 int copy_str_to_buffer(struct stun_msg* res, const char* data, UINT_T pad)
760 {
761         USHORT_T        pad_len;
762         UINT_T          data_len;
763         UCHAR_T         empty[pad];
764         
765         data_len = strlen(data);
766         memset(&empty, 0, pad);
767         
768         pad_len = pad - data_len%pad;
769         
770         if (buf_copy(&res->msg, (void *) data, sizeof(UCHAR_T)*data_len) != 0) {
771 #ifdef EXTRA_DEBUG
772                 LOG(L_DBG, "DEBUG: copy_str_to_buffer: failed to copy buffer\n");
773 #endif
774                 return FATAL_ERROR;
775         }
776         
777         if (pad_len != 0) {
778                 if (buf_copy(&res->msg, &empty, pad_len) != 0) {
779 #ifdef EXTRA_DEBUG
780                         LOG(L_DBG, "DEBUG: copy_str_to_buffer: failed to pad\n");
781 #endif
782                         return FATAL_ERROR;
783                 }       
784         }
785
786         return pad_len; 
787 }
788
789 /*
790  * stun_add_address_attr()
791  *                      - res: response representation
792  *                      - af: address family
793  *                      - port: port
794  *                      - ip_addr: represent both IPv4 and IPv6, the differences is in 
795  *                      length  
796  *                      - type: type of attribute
797  *                      - do_xor: if the port should be XOR-ed or not.
798  * 
799  * The function stun_add_address_attr ensures copy of any IP attribute into
800  * response buffer.
801  * 
802  * Return value:        0       if there is no environment error
803  *                                      -1      if there is some enviroment error such as insufficiency
804  *                                              of memory
805  */
806 int stun_add_address_attr(struct stun_msg* res, 
807                                                 UINT_T          af,
808                                                 USHORT_T        port,
809                                                 UINT_T*         ip_addr,
810                                                 USHORT_T        type,
811                                                 int do_xor)
812 {
813         struct stun_attr attr;
814         UINT_T   id[IP_ADDR];
815         int              ip_struct_len;
816         int i;
817         
818         ip_struct_len = 0;
819         attr.type = htons(type);
820         res->ip_addr.port = (do_xor) ? htons(port) ^ MAGIC_COOKIE_2B : htons(port);
821         switch(af) {
822                 case AF_INET:
823                         ip_struct_len = sizeof(struct stun_ip_addr) - 3*sizeof(UINT_T);
824                         res->ip_addr.family = htons(IPV4_FAMILY);
825                         memcpy(res->ip_addr.ip, ip_addr, IPV4_LEN);
826                         res->ip_addr.ip[0] = (do_xor) ? 
827                                         res->ip_addr.ip[0] ^ MAGIC_COOKIE : res->ip_addr.ip[0];         
828                         break;
829 #ifdef USE_IPV6
830                 case AF_INET6:
831                         ip_struct_len = sizeof(struct stun_ip_addr);
832                         res->ip_addr.family = htons(IPV6_FAMILY);
833                         memcpy(&res->ip_addr.ip, ip_addr, IPV6_LEN);
834                         memcpy(id, &res->hdr.id, sizeof(struct transaction_id));
835                         for (i=0; i<IP_ADDR; i++) {
836                                 res->ip_addr.ip[i] = (do_xor) ? 
837                                                         res->ip_addr.ip[i] ^ id[i] : res->ip_addr.ip[i];
838                         }
839                         break;
840 #endif /* USE_IPV6 */ 
841                 default:
842                         break;
843         }
844         
845         attr.len = htons(ip_struct_len);
846         
847         /* copy type and attribute's length */ 
848         if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
849                 return FATAL_ERROR;
850         }
851         
852         /* copy family, port and IP */
853         if (buf_copy(&res->msg, (void *) &res->ip_addr, ip_struct_len) != 0) {
854                 return FATAL_ERROR;
855         }
856
857         return 0;
858 }
859
860 /*
861  * add_fingerprint()
862  *                      - msg: response buffer
863  * 
864  * The function add_fingerprint ensures adding fingerprint attribute into
865  * response buffer.
866  * 
867  * Return value:        0       if there is no environment error
868  *                                      -1      if there is some enviroment error such as insufficiency
869  *                                              of memory
870  */
871 int add_fingerprint(struct stun_buffer* msg)
872 {
873         struct stun_attr attr;
874         USHORT_T attr_type_size;
875         
876         attr_type_size = sizeof(struct stun_attr);
877         attr.type = htons(FINGERPRINT_ATTR);
878         attr.len = htons(SHA_DIGEST_LENGTH);
879         
880         if (msg->empty < (SHA_DIGEST_LENGTH + attr_type_size)) {
881                 if (reallock_buffer(msg, SHA_DIGEST_LENGTH + attr_type_size) != 0) {
882                         return FATAL_ERROR;
883                 }
884         }
885         
886         memcpy(&msg->buf.s[msg->buf.len], (void *) &attr, attr_type_size);      
887         msg->buf.len += attr_type_size;
888         msg->empty -= attr_type_size;
889         
890         if (SHA1((UCHAR_T *)msg->buf.s, msg->buf.len-attr_type_size, 
891                          (UCHAR_T *) &msg->buf.s[msg->buf.len]) == 0) {
892                 LOG(L_ERR, "ERROR: STUN: SHA-1 algorithm failed.\n");
893                 return FATAL_ERROR;
894         }
895         
896         msg->buf.len += SHA_DIGEST_LENGTH;
897         msg->empty -= SHA_DIGEST_LENGTH;
898         
899         return 0;
900 }
901
902 /*
903  * stun_alloc_unknown_attr()
904  *                      - type: type of unknown attribute
905  * 
906  * The function stun_alloc_unknown_attr ensures allocationg new element for
907  * the link list of unknown attributes.
908  * 
909  * Return value: pointer to new element of link list in positive case
910  *                               NULL if there is some enviroment error such as insufficiency
911  *                                              of memory
912  */
913 struct stun_unknown_att* stun_alloc_unknown_attr(USHORT_T type)
914 {
915         struct stun_unknown_att* attr;
916
917         attr = (struct stun_unknown_att *) pkg_malloc(sizeof(struct stun_unknown_att));
918         if (attr == NULL) {
919                 LOG(L_ERR, "ERROR: STUN: out of memory\n");
920                 return NULL;
921         }
922         
923         attr->type = type;
924         attr->next = NULL;
925         
926         return attr;
927 }
928
929 /*
930  * stun_delete_unknown_attrs()
931  *                      - unknown: link list of unknown attributes
932  * 
933  * The function stun_delete_unknown_attrs ensures deleting of link list
934  * 
935  * Return value: none
936  */
937 void stun_delete_unknown_attrs(struct stun_unknown_att* unknown)
938 {
939         struct stun_unknown_att* tmp_unknown;
940         
941         if (unknown == NULL) {
942                 return;
943         }
944         
945         while(unknown->next) {
946                 tmp_unknown = unknown->next;
947                 unknown->next = tmp_unknown->next;
948                 pkg_free(tmp_unknown);          
949         }
950         pkg_free(unknown);
951 }
952
953 /*
954  * validate_fingerprint()
955  *                      - req: structure representing request message
956  *                      - error_code: indication of any protocol error
957  * 
958  * The function validate_fingerprint ensures validation of FINGERPRINT
959  * attribute.
960  * 
961  * Return value:        0       if there is no environment error
962  *                                      -1      if there is some enviroment error such as insufficiency
963  *                                              of memory
964  */
965 int validate_fingerprint(struct stun_msg* req, USHORT_T* error_code)
966 {
967         UCHAR_T msg_digest[SHA_DIGEST_LENGTH];
968         UINT_T  buf_len; 
969         
970         buf_len = req->hdr.len + sizeof(struct stun_hdr);
971         buf_len -= SHA_DIGEST_LENGTH + sizeof(struct stun_attr);
972         
973         if (SHA1((UCHAR_T *) req->msg.buf.s, buf_len, msg_digest) == 0) {
974                 LOG(L_ERR, "ERROR: STUN: SHA-1 algorithm failed.\n");
975                 return FATAL_ERROR;
976         } 
977         
978         if (memcmp((void *)req->fp, (void *)&msg_digest, SHA_DIGEST_LENGTH) != 0) {
979                 *error_code = BAD_REQUEST_ERR;
980         }
981         
982         return 0;       
983 }
984
985 /*
986  * buf_copy()
987  *                      - msg: buffer where the data will be copy to
988  *                      - source: source data buffer
989  *                      - len: number of bytes that should be copied
990  * 
991  * The function buf_copy copies "len" bytes from source into msg buffer
992  * 
993  * Return value:        0       if there is no environment error
994  *                                      -1      if there is some enviroment error such as insufficiency
995  *                                              of memory
996  */
997 int buf_copy(struct stun_buffer* msg, void* source, UINT_T len)
998 {
999         if (msg->empty < len) {
1000                 if (reallock_buffer(msg, len) != 0) {
1001                         return FATAL_ERROR;
1002                 }
1003         }
1004         
1005         memcpy(&msg->buf.s[msg->buf.len], source, len);
1006         msg->buf.len += len;
1007         msg->empty -= len;
1008         
1009         return 0;
1010 }
1011
1012 /*
1013  * reallock_buffer()
1014  *                      - buffer: original buffer
1015  *                      - len: represents minimum of bytes that must be available after 
1016  *                                      reallocation
1017  * 
1018  * The function reallock_buffer reallocks buffer. New buffer's length will be 
1019  * original length plus bigger from len and STUN_MSG_LEN constant.
1020  * 
1021  * Return value:        0       if there is no environment error
1022  *                                      -1      if there is some enviroment error such as insufficiency
1023  *                                              of memory
1024  */
1025 int reallock_buffer(struct stun_buffer* buffer, UINT_T len)
1026 {
1027         char*   tmp_buf;
1028         UINT_T  new_len;
1029         
1030         new_len = (STUN_MSG_LEN < len) ? STUN_MSG_LEN+len : STUN_MSG_LEN;
1031         
1032         tmp_buf = (char *) pkg_realloc(buffer->buf.s, 
1033                                                                    buffer->buf.len + buffer->empty + new_len);
1034         if (tmp_buf == 0) {
1035                 LOG(L_ERR, "ERROR: STUN: out of memory\n");
1036                 return FATAL_ERROR;
1037         }
1038         
1039         buffer->buf.s = tmp_buf;
1040         buffer->empty += new_len;
1041
1042         return 0;
1043 }
1044
1045 /*
1046  * clean_memory()
1047  *                      - res: structure representing response message
1048  *                      - unknown: link list of unknown attributes
1049  * 
1050  * The function clean_memory should free dynamic allocated memory.
1051  * 
1052  * Return value: none
1053  */
1054 void clean_memory(struct stun_msg* req,
1055                                 struct stun_msg* res,   struct stun_unknown_att* unknown)
1056 {
1057 #ifdef DYN_BUF
1058         pkg_free(req->msg.buf.s);
1059 #endif
1060
1061         if (res->msg.buf.s != NULL) {
1062                 pkg_free(res->msg.buf.s);
1063         }
1064         stun_delete_unknown_attrs(unknown);
1065 }
1066
1067 /*
1068  * stun_add_common_integer_attr()
1069  *                      - res: structure representing response
1070  *                      - type: type of attribute
1071  *                      - value: attribute's value
1072  * 
1073  * The function stun_add_common_integer_attr copy attribute with integer value 
1074  * into response buffer.
1075  * 
1076  * Return value:        0       if there is no environment error
1077  *                                      -1      if there is some enviroment error such as insufficiency
1078  *                                              of memory
1079  */
1080 int stun_add_common_integer_attr(struct stun_msg* res, 
1081                                                                  USHORT_T type, 
1082                                                                  UINT_T value)
1083 {
1084         struct stun_attr attr;
1085         
1086         attr.type = htons(type);
1087         attr.len = htons(sizeof(UINT_T));
1088         
1089         if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
1090                 return FATAL_ERROR;
1091         }
1092         
1093         value = htonl(value);
1094         if (buf_copy(&res->msg, (void *) &value, sizeof(UINT_T)) != 0) {
1095                 return FATAL_ERROR;
1096         }
1097         
1098         return 0;
1099 }
1100
1101 /*
1102  * stun_add_common_text_attr()
1103  *                      - res: structure representing response
1104  *                      - type: type of attribute
1105  *                      - value: attribute's value
1106  *                      - pad: size of pad
1107  * 
1108  * The function stun_add_common_text_attr copy attribute with string value 
1109  * into response buffer.
1110  * 
1111  * Return value:        0       if there is no environment error
1112  *                                      -1      if there is some enviroment error such as insufficiency
1113  *                                              of memory
1114  */
1115 int stun_add_common_text_attr(struct stun_msg* res, 
1116                                                           USHORT_T type, 
1117                                                           char* value, 
1118                                                           USHORT_T pad)
1119 {
1120         struct stun_attr attr;
1121         
1122         if (value == NULL) {
1123                 LOG(L_INFO, "INFO: stun_add_common_text_attr: value is NULL\n");
1124                 return 0;
1125         }
1126         
1127         attr.type = htons(type);
1128         attr.len = htons(strlen(value));
1129         
1130         if (buf_copy(&res->msg, (void *) &attr, sizeof(struct stun_attr)) != 0) {
1131                 return FATAL_ERROR;
1132         }
1133         
1134         if (copy_str_to_buffer(res, value, pad) < 0) {
1135                 return FATAL_ERROR;
1136         }
1137         
1138         return 0;
1139         
1140 }
1141
1142 #endif  /* USE_STUN */