sip.cpp 24 KB
Newer Older
savoirfairelinux's avatar
savoirfairelinux committed
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
/*
 * Copyright (C) 2004 Savoir-Faire Linux inc.
 * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> 
 *
 * Portions Copyright (C) 2002,2003   Aymeric Moizard <jack@atosc.org>
 *
 * This 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,
 * or (at your option) any later version.
 *
 * This 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 dpkg; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include <linux/socket.h>

#include <qlineedit.h>
#include <qcheckbox.h>

#include "audiocodec.h"
#include "configuration.h"
#include "global.h"
#include "sip.h"
#include "sipcall.h"

38 39 40 41 42
#include <string>
#ifdef  CCXX_NAMESPACES
using namespace std;
#endif

savoirfairelinux's avatar
savoirfairelinux committed
43 44 45 46 47 48 49 50 51 52
// TODO : mettre dans config
#define DEFAULT_SIP_PORT	5060
#define RANDOM_SIP_PORT		rand() % 64000 + 1024
#define	DEFAULT_LOCAL_PORT	10500
#define	RANDOM_LOCAL_PORT	((rand() % 27250) + 5250)*2


///////////////////////////////////////////////////////////////////////////////
// Thread implementation 
///////////////////////////////////////////////////////////////////////////////
53
EventThread::EventThread (SIP *sip) : Thread () {
savoirfairelinux's avatar
savoirfairelinux committed
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
	this->sipthread = sip;
}

/**
 * Reimplementation of run() to update widget
 */
void
EventThread::run (void) {
	for (;;) {
		sipthread->getEvent();
	}
}

///////////////////////////////////////////////////////////////////////////////
// SIP implementation
///////////////////////////////////////////////////////////////////////////////

SIP::SIP (Manager *_manager) {
	this->callmanager = _manager;
	this->myIPAddress = NULL;
	
	// For EventThread
	evThread = new EventThread (this);

	// Call init to NULL 
	for (int i = 0; i < NUMBER_OF_LINES; i++) {
		assert (i < NUMBER_OF_LINES);
		this->call[i] = NULL;
	}
	notUsedLine = -1;
}

SIP::~SIP (void) {
	if (evThread != NULL) {
		qDebug("SIP: delete evThread");
		delete evThread;
		evThread = NULL;
	}
	delete[] call;
	delete myIPAddress;
}

// Init eXosip and set user agent 
int
SIP::initSIP (void) {
	QString tmp;

	tmp = QString(PROGNAME) + "/" + QString(VERSION);

	// Set IP address
104 105
	if ( getLocalIp() == -1 )
		return -1;
savoirfairelinux's avatar
savoirfairelinux committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	
	srand (time(NULL));
	if (eXosip_init (NULL, NULL, DEFAULT_SIP_PORT) != 0) {
		if (eXosip_init (NULL, NULL, RANDOM_SIP_PORT) != 0) {
			qDebug("Cannot init eXosip");
			return -1;
		}
	}

	// If use STUN server, firewall address setup
	if (callmanager->useStun()) {
		eXosip_set_user_agent(tmp.ascii());
		StunAddress4 stunSvrAddr;
		stunSvrAddr.addr = 0;
		
		// Stun server
122 123
		string svr = Config::gets("Signalisations", "STUN.STUNserver");
		qDebug("address server stun = %s", svr.data());
savoirfairelinux's avatar
savoirfairelinux committed
124 125
		
		// Convert char* to StunAddress4 structure
126
		bool ret = stunParseServerName ((char*)svr.data(), stunSvrAddr);
savoirfairelinux's avatar
savoirfairelinux committed
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
		if (!ret) {
			qDebug("SIP: Stun server address not valid");
		}
		
		// Firewall address
		callmanager->getInfoStun(stunSvrAddr);
		eXosip_set_firewallip((callmanager->getFirewallAddress()).ascii());
	} 
	eXosip_set_user_agent(tmp.ascii());

	evThread->start();
	return 0;
}

void
SIP::quitSIP (void) {
	eXosip_quit();
}

bool
SIP::isInRtpmap (int index, int payload, AudioCodec &codec) {
	for (int i = 0; i < index; i++) {
		if (codec.handleCodecs[i] == payload) {
			return true;
		}
	}
	return false;
}

void
SIP::initRtpmapCodec (void) {
	int payload;
	char rtpmap[128];
	char tmp[64];

	bzero(rtpmap, 128);
	bzero(tmp, 64);
	
	AudioCodec codec;
 	/* reset all payload to fit application capabilities */
  	eXosip_sdp_negotiation_remove_audio_payloads();
	
	// Set rtpmap according to the supported codec order
	for (int i = 0; i < NB_CODECS; i++) {
		payload = codec.handleCodecs[i];

		// Add payload to rtpmap if it is not already added
		if (!isInRtpmap(i, payload, codec)) {
			snprintf(rtpmap, 127, "%d %s/%d", payload, 
					codec.rtpmapPayload(payload), SAMPLING_RATE);
			snprintf(tmp, 63, "%d", payload);
			
			eXosip_sdp_negotiation_add_codec( osip_strdup(tmp), NULL,
					   osip_strdup("RTP/AVP"), NULL, NULL, NULL, NULL,NULL,
					   osip_strdup(rtpmap));
		}
	}
#if 0    
  	eXosip_sdp_negotiation_add_codec(osip_strdup("111"),
				   NULL,
				   osip_strdup("RTP/AVP"),
				   NULL, NULL, NULL,
				   NULL,NULL,
				   osip_strdup("111 speex/16000"));

  /* Those attributes should be added for speex
     b=AS:110 20
     b=AS:111 20
  */
#endif
}

int 
SIP::getLocalIp (void) {
	if (myIPAddress == NULL) {
		myIPAddress = new char[64];
	}
	int ret = eXosip_guess_localip (2, myIPAddress, 64);
	return ret;
}

//Number of lines used
int
SIP::getNumberPendingCalls(void) {
  	int pos = 0;
  	int k;
  
  	for (k = 0; k < NUMBER_OF_LINES; k++) {
		assert (k < NUMBER_OF_LINES);
	    if (call[k]->state != NOT_USED) {
	  		pos++;
		}
    }
  	return pos;
}

// Return the first number of line not used
int
SIP::findLineNumberNotUsed (void) {
	int k;
	
	for (k = 0; k < NUMBER_OF_LINES; k++) {
		assert (k < NUMBER_OF_LINES);
		if (call[k] == NULL) {
			return k;
		}
    }

	// Every line is busy
	// TODO: ATTENTION AU RETOUR
	return -1;
}

// For ringing, answered, proceeding call
int
SIP::findLineNumber (eXosip_event_t *e) {
	int k;
	
	// Look for call with same cid/did
	for (k = 0; k < NUMBER_OF_LINES; k++) {
		if (call[k] != NULL) {
			if (call[k]->cid == e->cid and call[k]->did == e->did) {
				return k;
			}
		}
    }

	// If not found, return free line ?
	return findLineNumberNotUsed();
}

// For redirected, request,server,global failure, onhold, offhold call
int
SIP::findLineNumberUsed (eXosip_event_t *e) {
	return findLineNumber (e);
}

int
SIP::findLineNumberClosed (eXosip_event_t *e) {
	for (int k = 0; k < NUMBER_OF_LINES; k++) {
		if (call[k] != NULL) {
			if (call[k]->cid == e->cid) {
				return k;
			}
		} 
    }

	// TODO ATTENTION AU RETOUR
	return -1;
}
  
// Return call corresponding to pos
SipCall*
SIP::findCall (int pos) {
	for (int k = 0; k < NUMBER_OF_LINES; k++) {
		if (call[k] != NULL) {
			if (pos == 0) {
				return call[k];
			}
			pos--;
		}
	}
	return NULL;
}

int
SIP::checkURI (const char *buffer) {
	osip_uri_t *uri;
	int 		i;
	char 	   *dest = NULL;
	QString		qdest;

	qDebug("buffer = %s", buffer);
	// To parse a buffer containing a sip URI
	i = osip_uri_init(&uri);
	if (i != 0) {
		qWarning ("Cannot allocate");
	   	return -1; 
	}
	i = osip_uri_parse(uri, buffer);
	if (i != 0) { 
		qWarning("Cannot parse uri"); 
	}

	// Free memory
	osip_uri_free(uri);	
	osip_free(dest);
	return 0;	
}

// Parse url
int
SIP::checkUrl(char *url) {
  	int i;
	
  	osip_from_t *to;
  	i = osip_from_init(&to);
  	if (i != 0) {
		qWarning ("Cannot initialize");
		return -1;
	}
  	i = osip_from_parse(to, url);
  	if (i != 0) {
		qWarning ("Cannot parse url");
		return -1;
	}
  	return 0;
}

int
SIP::setRegister (void) {
	int reg_id = -1;

340 341
	string qproxy = "sip:" + Config::gets("Signalisations", "SIP.sipproxy"); 
	char * proxy = (char*)qproxy.data();
savoirfairelinux's avatar
savoirfairelinux committed
342

343 344 345 346 347 348 349
	string qhostname = "sip:" + Config::gets("Signalisations", "SIP.hostPart"); 
	char * hostname = (char*)qhostname.data();
	
	string qfrom = fromHeader(Config::gets("Signalisations", "SIP.userPart"), 
							Config::gets("Signalisations", "SIP.hostPart"));
	char * from = (char*)qfrom.data();
	
savoirfairelinux's avatar
savoirfairelinux committed
350 351 352 353 354 355 356 357 358 359 360
	qDebug("proxy = %s", proxy);
	qDebug("from = %s", from);

	if (from == NULL || proxy == NULL) {
		qDebug("ERROR:Proxy and from-URI required");
		return -1;
	}

	eXosip_lock();
	setAuthentication();
	
361
	if (Config::gets("Signalisations", "SIP.sipproxy") != "") {
savoirfairelinux's avatar
savoirfairelinux committed
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
		reg_id = eXosip_register_init(from, proxy, NULL);
	} else {
		reg_id = eXosip_register_init(from, hostname, NULL);
	}
	
	if (reg_id < 0) {
		eXosip_unlock();
		return -1;
	}	
	
	// TODO: port SIP session timer dans config
	int i = eXosip_register(reg_id, 3600);
	if (i == -2) {
		qDebug("cannot build registration, check the setup");
	}
	if (i == -1) {
		qDebug("Registration Failed");
	}
	
	eXosip_unlock();
	return 0;
}

int
SIP::setAuthentication (void) {
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
	string login, pass, realm;
	login = Config::gets("Signalisations", "SIP.username");
	if (login == "") {
		login = Config::gets("Signalisations", "SIP.userPart");
	}
	pass = Config::gets("Signalisations", "SIP.password");

	if (callmanager->useStun()) {
		realm = Config::gets("Signalisations", "SIP.hostPart");
	} else {
		if (Config::gets("Signalisations", "SIP.sipproxy") != "") {
			realm = Config::gets("Signalisations", "SIP.sipproxy");
		} else {
			realm = Config::gets("Signalisations", "SIP.hostPart");
		}
	}
	
	if (eXosip_add_authentication_info(login.data(), login.data(), 
		pass.data(), NULL, NULL) != 0) {
		qDebug ("No authentication");
		return -1;
	}
savoirfairelinux's avatar
savoirfairelinux committed
409 410 411
	return 0;
}
		
412 413 414 415
string
SIP::fromHeader (string user, string host) {
	return ("sip:" + user + "@" + host);
}
savoirfairelinux's avatar
savoirfairelinux committed
416

llea's avatar
llea committed
417

418 419 420 421 422 423 424 425
string
SIP::toHeader(string to) {
	if (to.find("sip:") == string::npos) {
		return ("sip:" + to );
	} else {
		return to;
	}
}
savoirfairelinux's avatar
savoirfairelinux committed
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

int
SIP::startCall ( char *from,  char *to,  char *subject,  char *route) {
  	osip_message_t *invite;
  	int i;

  	if (checkUrl(from) != 0) {
		qDebug("Error syntax for From header");
    	return -1;
  	}
  	if (checkUrl(to) != 0) {
		qDebug("Error syntax for To header");
    	return -1;
  	}
  	
	i = eXosip_build_initial_invite(&invite, to, from, route, subject);	
  	if (i != 0) {
		return -1;
    }
  	
	eXosip_lock();
	if (!callmanager->useStun()) {
		char port[64];

		// Set random port for outgoing call
		setLocalPort(RANDOM_LOCAL_PORT);

		bzero (port, 64);
		snprintf (port, 63, "%d", getLocalPort());
		
  		i = eXosip_initiate_call (invite, NULL, NULL, port);
		
	} else {
		QString qport;
		qport = qport.number(callmanager->getFirewallPort());
		
		i = eXosip_initiate_call(invite, NULL, NULL, (char*)qport.ascii());

		qDebug("sip invite: port = %s",(char*)qport.ascii());
	}
	if (i <= 0) {
		qDebug("NO initiate_call = %d", i);
		eXosip_unlock();
		return -1;
	}

	eXosip_unlock();
  	return i;	
}

int
SIP::outgoingInvite (void) {
	char * from;
	char * to;

481 482 483 484
	// Form the From header field basis on configuration panel
	string qfrom = fromHeader(Config::gets("Signalisations", "SIP.userPart"),
								Config::gets("Signalisations", "SIP.hostPart"));
	from = (char*)qfrom.data();
savoirfairelinux's avatar
savoirfairelinux committed
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
	// Form the To header field
	string qto = toHeader(string(callmanager->bufferTextRender().ascii()));
	if (qto.find("@") == string::npos and 
			Config::getb("Preferences", "Options.autoregister")) {
		qto = qto + "@" + Config::gets("Signalisations", "SIP.hostPart");
	}
	to = (char*)qto.data();
		
	qDebug ("From: <%s>", from);
	qDebug ("To: <%s>", to);

	// If no SIP proxy setting
	if (Config::gets("Signalisations", "SIP.sipproxy") == "") {
		if (startCall(from, to, NULL, NULL) <= 0) {
			qDebug("SIP: no start call");
			return -1;
		}
		return 0;
	}
	
	string qroute = "<sip:" + Config::gets("Signalisations", "SIP.sipproxy") 
							+ ";lr>";
	char * route = (char*)qroute.data();
	
	if (startCall(from, to, NULL, route) <= 0) {
		qDebug("SIP: no start call");
		return -1;
	}
savoirfairelinux's avatar
savoirfairelinux committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	return 0;
}

int
SIP::getLocalPort (void) {
	return local_port;
}

void
SIP::setLocalPort (int port) {
	this->local_port = port;
}
	
void
SIP::carryingDTMFdigits (int line, char digit) {
529
	  int duration = Config::geti("Signalisations", "DTMF.pulseLength"); 
savoirfairelinux's avatar
savoirfairelinux committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
      
	  static const int body_len = 128;

      char *dtmf_body = new char[body_len];
	  snprintf(dtmf_body, body_len - 1,
			  "Signal=%c\r\nDuration=%d\r\n",
			  digit, duration);

      eXosip_lock();
      eXosip_info_call(call[line]->did, "application/dtmf-relay", dtmf_body);
      eXosip_unlock();
	
	  delete[] dtmf_body;
}

545
// Handle IP-Phone user actions
savoirfairelinux's avatar
savoirfairelinux committed
546 547 548
int
SIP::manageActions (int usedLine, int action) {
	int i;
549 550 551
//	QString referTo;
	string referTo;
	
savoirfairelinux's avatar
savoirfairelinux committed
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 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
	char tmpbuf[64];

	assert (usedLine < NUMBER_OF_LINES);
	assert (usedLine >= 0);
	
	bzero (tmpbuf, 64);

	switch (action) {
		
	// IP-Phone user is answering a call.
	case ANSWER_CALL: 
		qDebug("ANSWER_CALL line %d, call = 0x%X, cid = %d, did = %d", 
				usedLine,  call[usedLine], call[usedLine]->cid, 
				call[usedLine]->did);

		callmanager->setCallInProgress(false);
		
		// Get local port
		snprintf (tmpbuf, 63, "%d", call[usedLine]->getLocalAudioPort());
		qDebug("getLocalAudioPort = %d",call[usedLine]->getLocalAudioPort());

		eXosip_lock();
		i = eXosip_answer_call(call[usedLine]->did, 200, tmpbuf);
		eXosip_unlock();
			
		// Incoming call is answered, start the sound channel.
		if (callmanager->startSound (call[usedLine]) < 0) {
			qDebug ("FATAL: Unable to start sound (%s:%d)",
					__FILE__, __LINE__);
			exit(1);
		}
		break;

	// IP-Phone user is hanging up.
	case CLOSE_CALL: // 1
		qDebug("CLOSE_CALL: cid = %d et did = %d", call[usedLine]->cid, 
				call[usedLine]->did);
		
		// Release SIP stack.
		eXosip_lock();
		i = eXosip_terminate_call (call[usedLine]->cid, call[usedLine]->did);
		eXosip_unlock();
		qDebug ("exosip_terminate_call = %d", i);

		// Release RTP channels
		call[usedLine]->closedCall();

		// Delete the call when I hangup
		if (call[usedLine] != NULL) {
			qDebug("SIP: CLOSE_CALL delete call[%d]", usedLine);
			delete call[usedLine];
			call[usedLine] = NULL;
		}
		break;

	// IP-Phone user is parking peer on HOLD
	case ONHOLD_CALL:
		qDebug("SIP ONHOLD:  call[%d] = 0x%X", usedLine, call[usedLine]);
		
		call[usedLine]->usehold = true;
		
		eXosip_lock();
		i = eXosip_on_hold_call(call[usedLine]->did);
		eXosip_unlock();
		
		// Disable audio
		callmanager->closeSound(call[usedLine]);
		break;

	// IP-Phone user is parking peer OFF HOLD
	case OFFHOLD_CALL:
		qDebug("SIP OFFHOLD: call[%d] = 0x%X", usedLine,call[usedLine]);

		call[usedLine]->usehold = true;

		eXosip_lock();
		i = eXosip_off_hold_call(call[usedLine]->did, NULL, 0);
		eXosip_unlock();

		// Enable audio
		if (callmanager->startSound (call[usedLine]) < 0) {
			qDebug ("FATAL: Unable to start sound (%s:%d)",
					__FILE__, __LINE__);
			exit(1);
		}
		break;

	// IP-Phone user is transfering call
	case TRANSFER_CALL:
641 642 643 644 645
		referTo	= toHeader(string(callmanager->bufferTextRender().ascii()));
		if (referTo.find("@") == string::npos) {
			referTo = referTo + "@" + 
				Config::gets("Signalisations", "SIP.hostPart");
		}
savoirfairelinux's avatar
savoirfairelinux committed
646 647
		
		eXosip_lock();
648
		i = eXosip_transfer_call(call[usedLine]->did, (char*)referTo.data());
savoirfairelinux's avatar
savoirfairelinux committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
		eXosip_unlock();
		break;
		
	// IP-Phone user is hanging up during ringing
	case CANCEL_CALL:
		qDebug("SIP: CANCEL_CALL: terminate cid=%d did=%d", 
				call[usedLine]->cid,call[usedLine]->did);
		eXosip_lock();
		i = eXosip_terminate_call (call[usedLine]->cid, call[usedLine]->did);
		eXosip_unlock();

		// Delete the call when I hangup
		if (call[usedLine] != NULL) {
			qDebug("SIP: CANCEL_CALL delete call[%d]", usedLine);
			delete call[usedLine];
			call[usedLine] = NULL;
		}
		break;

	default:
		return -1;
		break;
	}
	return 0;
}


// Receive events from the other
int
SIP::getEvent (void) {
	eXosip_event_t *event;
	int theline = -1;
llea's avatar
llea committed
681
	static int countReg = 0;
savoirfairelinux's avatar
savoirfairelinux committed
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

	event = eXosip_event_wait (0, 50);
	if (event == NULL) {
		return -1;
	}	
	
	qDebug("event_type = %d", event->type);
	callmanager->handleRemoteEvent(event->status_code,
			event->reason_phrase,
			-1);	
	switch (event->type) {
		// IP-Phone user receives a new call
		case EXOSIP_CALL_NEW: //13
			qDebug("<- (%i %i) INVITE from: %s", event->cid, event->did,
				event->remote_uri);

			// Set local random port for incoming call
			setLocalPort(RANDOM_LOCAL_PORT);
			
			theline = findLineNumberNotUsed();
			notUsedLine = theline;
			qDebug("%s: line number of new call = %d", __FILE__, notUsedLine);

			if (theline < 0) {
				// TODO: remonter erreur au manager (on refuse l'appel)
			}
			assert (theline >= 0); assert (theline < NUMBER_OF_LINES);

			if (call[theline] == NULL) {
				callmanager->setCallInProgress(true);
				qDebug("callmanager->setCallInProgress=%d",
						callmanager->getCallInProgress());
				
				call[theline] = new SipCall (callmanager);
				
				call[theline]->newIncomingCall(event);

				// Associate an audio port with a call
				call[theline]->setLocalAudioPort(local_port);

				// Visual blink signal and tone setup when somebody calls me
				callmanager->ring();
			}
			break;

		// The callee answers
		case EXOSIP_CALL_ANSWERED: // 8, start call: event->status_code = 200
			qDebug("ANSWERED<- (%i %i) [%i %s] %s", event->cid, event->did, 
				event->status_code, event->reason_phrase,
				event->remote_uri);
			   	
			// TODO: stop the ringtone
			callmanager->ringTone(false);
	
			// Stop the call progress
			callmanager->setCallInProgress(false);
			
			theline = findLineNumber(event);
			 
			if (call[theline] == NULL) {
				call[theline] = new SipCall(callmanager);
			}
			
			// Conditions to not start sound when callee answers for onhold
			// and offhold state
			if (callmanager->phLines[theline]->getStateLine() == BUSY or 
					callmanager->phLines[theline]->getStateLine() == OFFHOLD
					or !call[theline]->usehold) {
				if (!callmanager->transferedCall()) {
					// Associate an audio port with a call
					call[theline]->setLocalAudioPort(local_port);

					// Answer
					call[theline]->answeredCall(event);

					// Handle event
					callmanager->handleRemoteEvent (
							0, NULL, EXOSIP_CALL_ANSWERED);

					callmanager->setChoose (false, false);
					
					// Outgoing call is answered, start the sound channel.
					if (callmanager->startSound (call[theline]) < 0) {
						qDebug ("FATAL: Unable to start sound (%s:%d)",
							__FILE__, __LINE__);
						exit(1);
					}
				}
			}
			break;

		case EXOSIP_CALL_RINGING:
			qDebug("RINGING<- (%i %i) [%i %s] %s", event->cid, event->did, 
				event->status_code, event->reason_phrase, 
				event->remote_uri);
			
			callmanager->handleRemoteEvent (0, NULL, EXOSIP_CALL_RINGING);

			// If we have chosen the line before validating the phone number
			if (callmanager->isChosenLine() and !callmanager->otherLine()) {
				theline = callmanager->chosenLine();
			} else {
				theline = findLineNumber(event);
			}

			if (theline < 0) {
				// TODO: remonter erreur au manager (on refuse l'appel)
			}
			assert (theline >= 0);
			assert (theline < NUMBER_OF_LINES);

			call[theline] = new SipCall(callmanager);
			call[theline]->ringingCall(event);
			break;

		case EXOSIP_CALL_REDIRECTED:
			qDebug("REDIRECTED<- (%i %i) [%i %s] %s",event->cid, event->did,
				event->status_code, event->reason_phrase, 
				event->remote_uri);
			// theline = findLineNumberUsed(event);
			//assert (theline >= 0);
			//assert (theline < NUMBER_OF_LINES);
			//? call[theline] = new SipCall(callmanager);
			// call[theline]->redirectedCall(event);
			break;

		case EXOSIP_CALL_REQUESTFAILURE:
			qDebug("REQUESTFAILURE<- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase,
				event->remote_uri);
			// Handle 4XX errors
			switch (event->status_code) {
				case AUTH_REQUIRED:
					eXosip_lock();
					setAuthentication();
					eXosip_retry_call (event->cid);
					eXosip_unlock();
					break;
				case NOT_FOUND:
					callmanager->setCallInProgress(false);
					break;
				case ADDR_INCOMPLETE:
					callmanager->setCallInProgress(false);
					break;
				case FORBIDDEN:
					break;
				default:
					callmanager->setCallInProgress(false);
					break;
			}
			
			//theline = findLineNumberUsed(event);
			//assert (theline >= 0);
			//assert (theline < NUMBER_OF_LINES);
		//	call[theline]->requestfailureCall(event);
			break; 

		case EXOSIP_CALL_SERVERFAILURE:
			qDebug("SERVERFAILURE<- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase,
				event->remote_uri);
			//theline = findLineNumberUsed(event);
			//assert (theline >= 0);
			//assert (theline < NUMBER_OF_LINES);
		//	call[theline]->serverfailureCall(event);
			break;

		case EXOSIP_CALL_GLOBALFAILURE:
			qDebug("GLOBALFAILURE<- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase,
				event->remote_uri);
		//	call[findLineNumberUsed(event)]->globalfailureCall(event);
			break;

		// The remote peer closed the phone call(we received BYE).
		case EXOSIP_CALL_CLOSED:
			qDebug("<- (%i %i) BYE from: %s", event->cid, event->did, 
				event->remote_uri);

			if (!callmanager->getCallInProgress()) {
				// If callee answered before closing call 
				// or callee not onhold by caller
			 	theline = findLineNumberClosed(event);
				call[theline]->closedCall();
			} else {
				// If callee closes call instead of answering
				theline = notUsedLine;
			}

			assert (theline >= 0);
			assert (theline < NUMBER_OF_LINES);

			if (call[theline] != NULL) {
				delete call[theline];
				call[theline] = NULL;
				callmanager->handleRemoteEvent(0, NULL, EXOSIP_CALL_CLOSED);
			}
			break;

		case EXOSIP_CALL_HOLD:
			qDebug("<- (%i %i) INVITE (On Hold) from: %s", event->cid, 
				event->did, event->remote_uri);
			theline = findLineNumber(event);
			callmanager->closeSound(call[theline]);
			call[theline]->onholdCall(event);
			break;

		case EXOSIP_CALL_OFFHOLD:
			qDebug("<- (%i %i) INVITE (Off Hold) from: %s", event->cid, 
				event->did, event->remote_uri);
			theline = findLineNumber(event);
			if (callmanager->startSound (call[theline]) < 0) {
				qDebug ("FATAL: Unable to start sound (%s:%d)",
						__FILE__, __LINE__);
				exit(1);
			}
			call[theline]->offholdCall(event);
			break;

		case EXOSIP_REGISTRATION_SUCCESS:
			qDebug("REGISTRATION_SUCCESS <- (%i) [%i %s] %s for REGISTER %s", 
				event->rid, event->status_code, event->reason_phrase, 
				event->remote_uri, event->req_uri);
			callmanager->handleRemoteEvent(0,NULL,EXOSIP_REGISTRATION_SUCCESS);
			break;

		case EXOSIP_REGISTRATION_FAILURE:
			qDebug("REGISTRATION_FAILURE <- (%i) [%i %s] %s for REGISTER %s", 
				event->rid, event->status_code, event->reason_phrase, 
				event->remote_uri, event->req_uri);
llea's avatar
llea committed
912 913 914 915 916
			if (countReg <= 3) { 
				setRegister();
				countReg++;
			}
			callmanager->handleRemoteEvent(0,NULL,EXOSIP_REGISTRATION_FAILURE);
savoirfairelinux's avatar
savoirfairelinux committed
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
			break;

		case EXOSIP_OPTIONS_NEW:
			qDebug("OPT_NEW <- (%i %i) OPTIONS from: %s", event->cid, 
				event->did, event->remote_uri);

			/* answer the OPTIONS method */
			/* 1: search for an existing call */
			int k;
			for (k = 0; k < NUMBER_OF_LINES; k++) {
				if (call[k] != NULL) {
					if (call[k]->cid == event->cid) {
						break;
					}
				}
			}
				// TODO: Que faire si rien trouve??
			eXosip_lock();
			if (call[k]->cid == event->cid) {
				/* already answered! */
			}
			else if (k == NUMBER_OF_LINES) {
				/* answer 200 ok */
				eXosip_answer_options (event->cid, event->did, 200);
			} else {
				/* answer 486 ok */
				eXosip_answer_options (event->cid, event->did, 486);
			}
			eXosip_unlock();
			break;

		case EXOSIP_OPTIONS_ANSWERED:
			qDebug("OPT_ANSWERED <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_OPTIONS_PROCEEDING:
			qDebug("OPT_PROCEEDING <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_OPTIONS_REDIRECTED:
			qDebug("OPT_REDIR <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_OPTIONS_REQUESTFAILURE:
			qDebug ("OPT_REQ_FAIL <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_OPTIONS_SERVERFAILURE:
			qDebug("OPT_SVR_FAIL <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_OPTIONS_GLOBALFAILURE:
			qDebug("OPT_GL_FAIL <- (%i %i) [%i %s] %s", event->cid, 
				event->did, event->status_code, event->reason_phrase, 
				event->remote_uri);
			break;

		case EXOSIP_SUBSCRIPTION_NOTIFY:
			qDebug("SUBS_NOTIFY <- (%i %i) NOTIFY from: %s", event->sid, 
				event->did, event->remote_uri);
			qDebug("<- (%i %i) online=%i [status: %i reason:%i]",
				event->sid, event->did, event->online_status, 
				event->ss_status, event->ss_reason);
			//subscription_notify(je);
			break;

		default:
			return -1;
			break;
	}
	eXosip_event_free(event);
 	
    return 0;
}