Codebase list sipp / master message.cpp
master

Tree @master (Download .tar.gz)

message.cpp @masterraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Author : Richard GAYRAUD - 04 Nov 2003
 *           Olivier Jacques
 *           From Hewlett Packard Company.
 *           Shriram Natarajan
 *           Peter Higginson
 *           Eric Miller
 *           Venkatesh
 *           Enrico Hartung
 *           Nasir Khan
 *           Lee Ballard
 *           Guillaume Teissier from FTR&D
 *           Wolfgang Beck
 *           Venkatesh
 *           Vlad Troyanker
 *           Charles P Wright from IBM Research
 *           Amit On from Followap
 *           Jan Andres from Freenet
 *           Ben Evans from Open Cloud
 *           Marc Van Diest from Belgacom
 *	     Stefan Esser
 *           Andy Aicken
 */

#include "sipp.hpp"
#include "message.hpp"

struct KeywordMap {
	char *keyword;
	MessageCompType type;
};

typedef std::map<std::string, customKeyword> kw_map;
kw_map keyword_map;

/* These keywords take no parameters. */
struct KeywordMap SimpleKeywords[] = {
  {"remote_ip", E_Message_Remote_IP },
  {"remote_host", E_Message_Remote_Host },
  {"remote_port", E_Message_Remote_Port },
  {"transport", E_Message_Transport },
  {"local_ip", E_Message_Local_IP },
  {"local_ip_type", E_Message_Local_IP_Type },
  {"local_port", E_Message_Local_Port },
  {"server_ip", E_Message_Server_IP },
  {"media_ip", E_Message_Media_IP },
#ifdef PCAPPLAY
  {"auto_media_port", E_Message_Auto_Media_Port },
#endif
  {"media_port", E_Message_Media_Port },
  {"media_ip_type", E_Message_Media_IP_Type },
  {"call_number", E_Message_Call_Number },
  {"dynamic_id", E_Message_DynamicId }, // wrapping global counter
  {"call_id", E_Message_Call_ID },
  {"cseq", E_Message_CSEQ },
  {"pid", E_Message_PID },
  {"service", E_Message_Service },
  {"branch", E_Message_Branch },
  {"msg_index", E_Message_Index },
  {"next_url", E_Message_Next_Url },
  {"len", E_Message_Len },
  {"peer_tag_param", E_Message_Peer_Tag_Param },
  {"last_Request_URI", E_Message_Last_Request_URI },
  {"last_cseq_number", E_Message_Last_CSeq_Number },
  {"last_message", E_Message_Last_Message },
  {"routes", E_Message_Routes },
  {"tdmmap", E_Message_TDM_Map },
  {"clock_tick", E_Message_ClockTick },
  {"users", E_Message_Users },
  {"userid", E_Message_UserID },
  {"timestamp", E_Message_Timestamp },
  {"sipp_version", E_Message_SippVersion },
};

#define KEYWORD_SIZE 256

SendingMessage::SendingMessage(scenario *msg_scenario, char *src, bool skip_sanity) {
    char *osrc = src;
    char * literal;
    int    literalLen;
    char * dest;
    char * key;
    char   current_line[MAX_HEADER_LEN];
    char * line_mark = NULL;
    char * tsrc;
    int    num_cr = get_cr_number(src);

    this->msg_scenario = msg_scenario;
    
    dest = literal = (char *)malloc(strlen(src) + num_cr + 1);
    literalLen = 0;
 
    current_line[0] = '\0';
    *dest = 0;

    while(*src) {
      if (current_line[0] == '\0') {
        line_mark = strchr(src, '\n');
        if (line_mark) {
          int header_len =  line_mark - src;
          if (header_len > MAX_HEADER_LEN-1)
              header_len = MAX_HEADER_LEN-1;
          memcpy(current_line, src, header_len);
          current_line[header_len] = '\0';
        }
      }

      /* This hex encoding could be done in XML parsing, allowing us to skip
       * these conditionals and branches. */
      if ((*src == '\\') && (*(src+1) == 'x')) {
        /* Allows any hex coded char like '\x5B' ([) */
        src += 2;
        if (isxdigit(*src)) {
          int val = get_decimal_from_hex(*src);
          src++;
          if (isxdigit(*src)) {
            val = (val << 4) + get_decimal_from_hex(*src);
          }
          *dest++ = val & 0xff;
        }
        src++;
      } else if (*src == '\n') {
        *dest++ = '\r';
        *dest++ = *src++;
        current_line[0] = '\0';
      } else if (*src != '[') {
        *dest++ = *src++;
      } else {
	/* We have found a keyword, store the literal that we have been generating. */
        literalLen = dest - literal;
	if (literalLen) {
	  *dest = '\0';
	  literal = (char *)realloc(literal, literalLen + 1);
	  if (!literal) { ERROR("Out of memory!"); }

	  MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
	  if (!newcomp) { ERROR("Out of memory!"); }

	  newcomp->type = E_Message_Literal;
	  newcomp->literal = literal;
	  newcomp->literalLen = literalLen; // length without the terminator 
	  messageComponents.push_back(newcomp);
	} else {
	  free(literal);
	}

	dest = literal = (char *)malloc(strlen(src) + num_cr + 1);
	literalLen = 0;
	*dest = '\0';

	/* Now lets determine which keyword we have. */
	MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
	if (!newcomp) { ERROR("Out of memory!"); }

        char keyword [KEYWORD_SIZE+1];
	src++;

	/* Like strchr, but don't count things in quotes. */
	for(tsrc = src; *tsrc; tsrc++) {
		if (*tsrc == '\"') {
			do {
				tsrc++;
			} while(*tsrc && *tsrc != '\"');
			if (!*tsrc) {
				break;
			}
		}
		if (*tsrc == '[')
			break;
	}
	if (*tsrc != '[') {
		tsrc = NULL;
	}

	/* Like strchr, but don't count things in quotes. */
	for(key = src; *key; key++) {
		if (*key == '\"') {
			do {
				key++;
			} while(*key && *key != '\"');
		}
		if (*key == ']')
			break;
	}
	if (*key != ']') {
		key = NULL;
	}

        if ((tsrc) && (tsrc<key)){
          memcpy(keyword, src-1,  tsrc - src + 1);
          src=tsrc+1;
          dest += sprintf(dest, "%s", keyword);
        }

	if((!key) || ((key - src) > KEYWORD_SIZE) || (!(key - src))){
          ERROR("Syntax error or invalid [keyword] in scenario while parsing '%s'", current_line);
        }
        memcpy(keyword, src,  key - src);
	keyword[key - src] = 0;
        src = key + 1;
        // allow +/-n for numeric variables
	newcomp->offset = 0;
        if ((strncmp(keyword, "authentication", strlen("authentication")) &&
	    strncmp(keyword, "tdmmap", strlen("tdmmap"))) &&
	    ((key = strchr(keyword,'+')) || (key = strchr(keyword,'-')))) {
	    if (isdigit(*(key+1))) {
	      newcomp->offset = atoi(key);
		*key = 0;
	    }
	}

	char *spc = NULL;
	char ospc;
	if ((spc = strchr(keyword, ' '))) {
		ospc = *spc;
		*spc = '\0';
	}
	kw_map::iterator it = keyword_map.find(keyword);
	if (spc) {
	  *spc = ospc;
	}

	if (it != keyword_map.end()) {
	  newcomp->type = E_Message_Custom;
	  newcomp->comp_param.fxn = it->second;
	  messageComponents.push_back(newcomp);
	  continue;
	}

	bool simple_keyword = false;
	for (unsigned int i = 0; i < sizeof(SimpleKeywords)/sizeof(SimpleKeywords[0]); i++) {
	  if (!strcmp(keyword, SimpleKeywords[i].keyword)) {
		newcomp->type = SimpleKeywords[i].type;
		simple_keyword = true;
		break;
	  }
	}

	if (simple_keyword) {
	  messageComponents.push_back(newcomp);
	  continue;
	}

        if(!strncmp(keyword, "field", strlen("field"))) {
	  newcomp->type = E_Message_Injection;

	  /* Parse out the interesting things like file and number. */
	  newcomp->comp_param.field_param.field = atoi(keyword + strlen("field"));

	  char fileName[KEYWORD_SIZE];
	  getKeywordParam(keyword, "file=", fileName);
	  if (fileName[0] == '\0') {
	    if (!default_file) {
	      ERROR("No injection file was specified!\n");
	    }
	    newcomp->comp_param.field_param.filename = strdup(default_file);
	  } else {
	    newcomp->comp_param.field_param.filename = strdup(fileName);
	  }
	  if (inFiles.find(newcomp->comp_param.field_param.filename) == inFiles.end()) {
	    ERROR("Invalid injection file: %s\n", fileName);
	  }

	  char line[KEYWORD_SIZE];
	  getKeywordParam(keyword, "line=", line);
	  if (line[0]) {
	    /* Turn this into a new message component. */
	    newcomp->comp_param.field_param.line = new SendingMessage(msg_scenario, line, true);
	  }
        } else if(!strncmp(keyword, "file", strlen("file"))) {
	  newcomp->type = E_Message_File;

	  /* Parse out the interesting things like file and number. */
	  char fileName[KEYWORD_SIZE];
	  getKeywordParam(keyword, "name=", fileName);
	  if (fileName[0] == '\0') {
	    ERROR("No name specified for 'file' keyword!\n");
	  }
	  /* Turn this into a new message component. */
	  newcomp->comp_param.filename = new SendingMessage(msg_scenario, fileName, true);
        } else if(*keyword == '$') {
	  newcomp->type = E_Message_Variable;
	  if (!msg_scenario) {
	    ERROR("SendingMessage with variable usage outside of scenario!");
	  }
	  newcomp->varId = msg_scenario->get_var(keyword + 1, "Variable keyword");
	} else if(!strncmp(keyword, "fill", strlen("fill"))) {
	  newcomp->type = E_Message_Fill;
	  char filltext[KEYWORD_SIZE];
	  char varName[KEYWORD_SIZE];

	  getKeywordParam(keyword, "text=", filltext);
	  if (filltext[0] == '\0') {
	    strcpy(filltext, "X");
	  }
	  getKeywordParam(keyword, "variable=", varName);

	  newcomp->literal = strdup(filltext);
	  newcomp->literalLen = strlen(newcomp->literal);
	  if (!msg_scenario) {
	    ERROR("SendingMessage with variable usage outside of scenario!");
	  }
	  newcomp->varId = msg_scenario->get_var(varName, "Fill Variable");
     } else if(!strncmp(keyword, "last_", strlen("last_"))) {
       newcomp->type = E_Message_Last_Header;
       newcomp->literal = strdup(keyword + strlen("last_"));
       newcomp->literalLen = strlen(newcomp->literal);
     } else if(!strncmp(keyword, "authentication", strlen("authentication"))) {
       parseAuthenticationKeyword(msg_scenario, newcomp, keyword);
     }
#ifndef PCAPPLAY
        else if(!strcmp(keyword, "auto_media_port") ||
		  !strcmp(keyword, "media_port") ||
		  !strcmp(keyword, "media_ip") ||
		  !strcmp(keyword, "media_ip_type")) {
	  ERROR("The %s keyword requires PCAPPLAY.\n", keyword);
	}
#endif
	else {
	  // scan for the generic parameters - must be last test

          int i = 0;
          while (generic[i]) {
            char *msg1 = *generic[i];
            char *msg2 = *(generic[i] + 1);
            if(!strcmp(keyword, msg1)) {
	      newcomp->type = E_Message_Literal;
	      newcomp->literal = strdup(msg2);
	      newcomp->literalLen = strlen(newcomp->literal);
              break;
            }
            ++i;
          }
          if (!generic[i]) {
            ERROR("Unsupported keyword '%s' in xml scenario file",
                   keyword);
          }
	}

	messageComponents.push_back(newcomp);
      }
    }
    if (literal[0]) {
      *dest++ = '\0';
      literalLen = dest - literal;
      literal = (char *)realloc(literal, literalLen);
      if (!literal) { ERROR("Out of memory!"); } 

      MessageComponent *newcomp = (MessageComponent *)calloc(1, sizeof(MessageComponent));
      if (!newcomp) { ERROR("Out of memory!"); }

      newcomp->type = E_Message_Literal;
      newcomp->literal = literal;
      newcomp->literalLen = literalLen-1;
      messageComponents.push_back(newcomp);
    } else {
      free(literal);
    }

    if (skip_sanity) {
      cancel = response = ack = false;
      method = NULL;
      return;
    }

    if (numComponents() < 1) {
	ERROR("Can not create a message that is empty!");
    }
    if (getComponent(0)->type != E_Message_Literal) {
	ERROR("You can not use a keyword for the METHOD or to generate \"SIP/2.0\" to ensure proper [cseq] operation!\n%s\n", osrc);
    }

    char *p = method = strdup(getComponent(0)->literal);
    char *q;
    while (isspace(*p)) {
	p++;
    }
    if (!(q = strchr(method, ' '))) {
	ERROR("You can not use a keyword for the METHOD or to generate \"SIP/2.0\" to ensure proper [cseq] operation!%s\n", osrc);
    }
    *q++ = '\0';
    while (isspace(*q)) { q++; }
    if (!strcmp(method, "SIP/2.0")) {
	char *endptr;
	code = strtol(q, &endptr, 10);
	if (*endptr && !isspace(*endptr)) {
	  ERROR("Invalid reply code: %s\n", q);
	}
	if (code < 100 || code >= 700) {
	  ERROR("Response codes must be in the range of 100-700");
	}
	response = true;
	ack = false;
	cancel = false;
	free(method);
	method = NULL;
    } else {
      if (p != method) {
	memmove(method, p, strlen(p) + 1);
      }
      method = (char *)realloc(method, strlen(method) + 1);
      if (!method) { ERROR("Out of memory"); }
      ack = (!strcmp(method, "ACK"));
      cancel = (!strcmp(method, "CANCEL"));
      response = false;
    }
}

SendingMessage::~SendingMessage() {
  for (int i = 0; i < numComponents(); i++) {
    freeMessageComponent(messageComponents[i]);
  }
  free(method);
}

bool SendingMessage::isAck() { return ack; }
bool SendingMessage::isCancel() { return cancel; }
bool SendingMessage::isResponse() { return response; }
char *SendingMessage::getMethod() { return method; }
int SendingMessage::getCode() { return code; }

void SendingMessage::getQuotedParam(char * dest, char * src, int * len)
{
  *len=0;
  /* Allows any hex coded string like '0x5B07F6' */
  while (char c = *src++) {
    switch(c) {
      case '"':
	*len++;
	*dest = '\0';
	return;
      case '\\':
	c = *src++;
	*len++;
	if (c == 0) {
	  *dest = '\0';
	  return;
	}
	/* Fall-Through. */
      default:
	*dest++ = c;
	*len++;
    }
  }
  *dest = '\0';
}

void SendingMessage::getHexStringParam(char * dest, char * src, int * len)
{
  *len=0;
  /* Allows any hex coded string like '0x5B07F6' */
  while (isxdigit(*src)) {
    int val = get_decimal_from_hex(*src);
    src++;
    if (isxdigit(*src)) {
      val = (val << 4) + get_decimal_from_hex(*src);
      src++;
    }
    *dest++ = val & 0xff;
    (*len)++;
  }
}

void SendingMessage::getKeywordParam(char * src, char * param, char * output)
{
  char *key, *tmp;
  int len;

  len = 0;
  key = NULL;
  if ((tmp = strstr(src, param))) {
    tmp += strlen(param);
    key = tmp;
    if ((*key == '0') && (*(key+1) == 'x')) {
      key += 2;
      getHexStringParam(output, key, &len);
      key += len * 2;
    } else if (*key == '\"') {
      key++;
      getQuotedParam(output, key, &len);
      key += len;
    } else {
      while (*key) {
        if (((key - src) > KEYWORD_SIZE) || (!(key - src))) {
          ERROR("Syntax error parsing '%s' parameter", param);
        } else if (*key == ']' || *key < 33 || *key > 126) {
          break;
        }
        key++;
      }
      strncpy(output, tmp, key-tmp);
      output[key-tmp] = '\0';
    }
  } else {
    output[0] = '\0';
  }
}

void SendingMessage::parseAuthenticationKeyword(scenario *msg_scenario, struct MessageComponent *dst, char *keyword) {
  char my_auth_user[KEYWORD_SIZE + 1];
  char my_auth_pass[KEYWORD_SIZE + 1];
  char my_aka[KEYWORD_SIZE + 1];

  dst->type = E_Message_Authentication;

  memset(my_auth_user,0,KEYWORD_SIZE);
  memset(my_auth_pass,0,KEYWORD_SIZE);
  /* Look for optional username and password parameters */
  getKeywordParam(keyword, "username=", my_auth_user);
  getKeywordParam(keyword, "password=", my_auth_pass);

  if(*my_auth_user == '\0') {
    strcpy(my_auth_user, auth_username ? auth_username : service);
  }
  if(*my_auth_pass == '\0') {
    strcpy(my_auth_pass, auth_password);
  }


  dst->comp_param.auth_param.auth_user = new SendingMessage(msg_scenario, my_auth_user, true /* skip sanity */);
  dst->comp_param.auth_param.auth_pass = new SendingMessage(msg_scenario, my_auth_pass, true);

  /* add aka_OP, aka_AMF, aka_K */
  getKeywordParam(keyword, "aka_K=", my_aka);
  if (my_aka[0]==0){
    memcpy(my_aka,my_auth_pass,16);
    my_aka[16]=0;
  }
  dst->comp_param.auth_param.aka_K = new SendingMessage(msg_scenario, my_aka, true);

  getKeywordParam(keyword, "aka_OP=", my_aka);
  dst->comp_param.auth_param.aka_OP = new SendingMessage(msg_scenario, my_aka, true);
  getKeywordParam(keyword, "aka_AMF=", my_aka);
  dst->comp_param.auth_param.aka_AMF = new SendingMessage(msg_scenario, my_aka, true);
}

void SendingMessage::freeMessageComponent(struct MessageComponent *comp) {
  free(comp->literal);
  if (comp->type == E_Message_Authentication) {
    if (comp->comp_param.auth_param.auth_user) {
      delete comp->comp_param.auth_param.auth_user;
    }
    if (comp->comp_param.auth_param.auth_pass) {
      delete comp->comp_param.auth_param.auth_pass;
    }
    if (comp->comp_param.auth_param.aka_K) {
      delete comp->comp_param.auth_param.aka_K;
    }
    if (comp->comp_param.auth_param.aka_AMF) {
      delete comp->comp_param.auth_param.aka_AMF;
    }
    if (comp->comp_param.auth_param.aka_OP) {
      delete comp->comp_param.auth_param.aka_OP;
    }
  } else if (comp->type == E_Message_Injection) {
    free(comp->comp_param.field_param.filename);
  }
  free(comp);
}

int SendingMessage::numComponents() {
  return messageComponents.size();
}
struct MessageComponent *SendingMessage::getComponent(int i) {
  return messageComponents[i];
}

/* This is very simplistic and does not yet allow any arguments, but it is a start. */
int registerKeyword(char *keyword, customKeyword fxn) {
	if (keyword_map.find(keyword) != keyword_map.end()) {
		ERROR("Can not register keyword '%s', already registered!\n", keyword);
	}
	keyword_map[keyword] = fxn;
	return 0;
}