Blame view

sip/SipServer.cpp 30.8 KB
c887a0f0   Hu Chunming   提交初成版代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  //

  // Created bxc on 2022/11/25.

  //

  

  #include "SipServer.h"

  

  #ifndef WIN32

  // Linux系统

  #include <arpa/inet.h>

  #else

  #include <WinSock2.h>

  #pragma comment(lib, "ws2_32.lib")

  #endif // !WIN32

  

  #include <cstring>

  #include "./Utils/HTTPDigest.h"

  #include "./Utils/Utools.hpp"

  #include "./Utils/logger.hpp"

  #include "./Utils/StringTools.hpp"

  

  

  #include <sstream>

  #include <algorithm>

  

c887a0f0   Hu Chunming   提交初成版代码
25
26
27
28
29
30
31
32
33
34
35
36
37
  

  using namespace std;

  

  static void event_loop_thread(void* arg) {

      SipServer* _this = (SipServer*)arg;

      if (_this != nullptr) {

          _this->event_loop();

      }

      else {

          LOG_ERROR("event_loop线程启动失败 !");

      }

  }

  

c887a0f0   Hu Chunming   提交初成版代码
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  static void dt_printSipMsg(osip_message_t* msg) {

      osip_message_t* clone_event = NULL;

      size_t length = 0;

      char* message = NULL;

      osip_message_clone(msg, &clone_event);

      osip_message_to_str(clone_event, &message, &length);

      LOG_INFO("{}", message);

  }

  

  SipServer::SipServer():

          mQuit(false),

          mSipCtx(nullptr){

  #ifdef WIN32

      WSADATA wsaData;

      if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)

      {

          LOG_ERROR("WSAStartup Error");

          return;

      }

  #endif // WIN32

  

10821ac3   Hu Chunming   1.定时刷新设备目录;
59
60
61
      mClientMap.clear();

      m_device_map.clear();

  

c887a0f0   Hu Chunming   提交初成版代码
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
  }

  SipServer::~SipServer() {

      LOG_INFO("~SipServer");

  

      if (m_event_loop_thread)

      {

          mQuit = true;

          m_event_loop_thread->join();

  

          delete m_event_loop_thread;

          m_event_loop_thread = nullptr;

      }

  

      this->clearClientMap();

  #ifdef WIN32

      WSACleanup();

  #endif // WIN32

  }

  

e918c2a7   Hu Chunming   call release 自动重新...
81
  bool SipServer::Init(ServerInfo* pInfo, WebSocketServer* pServer) {

c887a0f0   Hu Chunming   提交初成版代码
82
  

e918c2a7   Hu Chunming   call release 自动重新...
83
      if (pInfo == nullptr || pServer == nullptr) {

c887a0f0   Hu Chunming   提交初成版代码
84
85
86
87
88
         return false;

      }

      

      mInfo = *pInfo;

  

e975618a   Hu Chunming   1.初始化 添加是否鉴权模式的日志
89
90
91
92
93
94
      if (mInfo.isNoAuth()) {

          LOG_INFO("do not need password");

      } else {

          LOG_INFO("need password");

      }

  

e918c2a7   Hu Chunming   call release 自动重新...
95
96
      m_pWsServer = pServer;

  

c887a0f0   Hu Chunming   提交初成版代码
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
      m_event_loop_thread = new std::thread(event_loop_thread, this);

  

      return true;

  }

  

  int SipServer::sip_event_handle(eXosip_event_t *evtp) {

  

      switch(evtp->type) {

          case EXOSIP_CALL_MESSAGE_NEW://14

              // LOG_INFO("EXOSIP_CALL_MESSAGE_NEW type={}", evtp->type);

              this->dump_request(evtp);

              this->dump_response(evtp);

              break;

  

          case EXOSIP_CALL_CLOSED://21

              LOG_INFO("EXOSIP_CALL_CLOSED type={}",evtp->type);

e918c2a7   Hu Chunming   call release 自动重新...
113
114
              // this->dump_request(evtp);

              // this->dump_response(evtp);

c887a0f0   Hu Chunming   提交初成版代码
115
116
117
118
              break;

  

          case EXOSIP_CALL_RELEASED://22

              LOG_INFO("EXOSIP_CALL_RELEASED type={}", evtp->type);

e918c2a7   Hu Chunming   call release 自动重新...
119
120
121
              reInvite(evtp->cid);

              // this->dump_request(evtp);

              // this->dump_response(evtp);

c887a0f0   Hu Chunming   提交初成版代码
122
123
124
125
126
127
128
  

              // this->clearClientMap();

              break;

          case EXOSIP_MESSAGE_NEW://23

              // LOG_INFO("EXOSIP_MESSAGE_NEW type={}",evtp->type);

  

              if (MSG_IS_REGISTER(evtp->request)) {

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
129
130
131
132
133
                  if (mInfo.isNoAuth()) {

                      response_register_noauth(evtp);

                  } else {

                      response_register(evtp);

                  }

c887a0f0   Hu Chunming   提交初成版代码
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
              }

              else if (MSG_IS_MESSAGE(evtp->request)) {

                  this->response_message(evtp);

              }

              else if(MSG_IS_BYE(evtp->request)){

                  LOG_ERROR("BYE");

              }

              else{

                  LOG_ERROR("unknown2");

              }

              break;

          case EXOSIP_MESSAGE_ANSWERED:

              this->dump_request(evtp);

              break;

          case EXOSIP_MESSAGE_REQUESTFAILURE:

              LOG_INFO("EXOSIP_MESSAGE_REQUESTFAILURE type={}: Receive feedback on sending failure after actively sending a message", evtp->type);

              this->dump_request(evtp);

              this->dump_response(evtp);

              break;

          case EXOSIP_CALL_INVITE:

              LOG_INFO("EXOSIP_CALL_INVITE type={}: The server receives the Invite request actively sent by the client", evtp->type);

              break;

          case EXOSIP_CALL_PROCEEDING://5

              LOG_INFO("EXOSIP_CALL_PROCEEDING type={}: When the server receives the Invite (SDP) confirmation reply from the client", evtp->type);

              this->dump_request(evtp);

              this->dump_response(evtp);

              break;

          case EXOSIP_CALL_ANSWERED:// 7

              LOG_INFO("EXOSIP_CALL_ANSWERED type={}: The server receives an invite (SDP) confirmation reply from the client", evtp->type);

              this->dump_request(evtp);

              this->dump_response(evtp);

  

              this->response_invite_ack(evtp);

              cache_invite_callinfo(evtp);

              break;

          case EXOSIP_CALL_SERVERFAILURE:

e918c2a7   Hu Chunming   call release 自动重新...
170
              LOG_INFO("EXOSIP_CALL_SERVERFAILURE cid={}", evtp->cid);

c887a0f0   Hu Chunming   提交初成版代码
171
172
              break;

          case EXOSIP_IN_SUBSCRIPTION_NEW:

e918c2a7   Hu Chunming   call release 自动重新...
173
174
175
176
              LOG_INFO("EXOSIP_IN_SUBSCRIPTION_NEW cid={}", evtp->cid);

              break;

          case EXOSIP_CALL_MESSAGE_ANSWERED:

              LOG_INFO("EXOSIP_CALL_MESSAGE_ANSWERED cid={}", evtp->cid);

c887a0f0   Hu Chunming   提交初成版代码
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
              break;

          default:

              LOG_INFO("type={} unknown", evtp->type);

              break;

      }

  

      return 0;

  }

  

  string contract_ip_from_message(string str_msg) {

  

      str_msg = StringTools::to_lower(str_msg);

  

      string c = str_msg.substr(str_msg.find("c=")+2);

      string c1 = c.substr(0, c.find_first_of("=") - 1);

      string c2 = c1.substr(c1.find_first_of("4")+1);

  

      return StringTools::trim(c2);

  }

  

  string contract_port_from_message(string str_msg) {

  

      str_msg = StringTools::to_lower(str_msg);

  

      string c = str_msg.substr(str_msg.find("video")+6);

      string c1 = c.substr(0, c.find_first_of(" "));

  

      return StringTools::trim(c1);

  }

  

  void SipServer::cache_invite_callinfo(eXosip_event_t *evtp) {

      CallInfo call_info;

      call_info.cid = evtp->cid;

      call_info.did = evtp->did;

  

      try

      {

          char *s;

          size_t len;

          osip_message_to_str(evtp->request, &s, &len);

  

          string ip = contract_ip_from_message(s);

          string port = contract_port_from_message(s);

  

e918c2a7   Hu Chunming   call release 自动重新...
221
          LOG_INFO("ip:{}  port:{}", ip, port);

c887a0f0   Hu Chunming   提交初成版代码
222
223
224
225
  

          string channel_id = evtp->response->to->url->username;

  

          auto key = std::make_tuple(channel_id, ip, atoi(port.c_str()));

e918c2a7   Hu Chunming   call release 自动重新...
226
227
  

          std::lock_guard<std::mutex> l(m_invite_callinfo_map_mtx);

c887a0f0   Hu Chunming   提交初成版代码
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
          m_invite_callinfo_map[key] = call_info;

      }

      catch(const std::exception& e)

      {

          std::cerr << e.what() << '\n';

      }

  }

  

  int SipServer::init_sip_server() {

      mSipCtx = eXosip_malloc();

      if (!mSipCtx) {

          LOG_ERROR("eXosip_malloc error");

          return -1;

      }

      if (eXosip_init(mSipCtx)) {

          LOG_ERROR("eXosip_init error");

          return -1;

      }

      if (eXosip_listen_addr(mSipCtx, IPPROTO_UDP, nullptr, mInfo.getPort(), AF_INET, 0)) {

          LOG_ERROR("eXosip_listen_addr error");

          return -1;

      }

      eXosip_set_user_agent(mSipCtx, mInfo.getUa().c_str());

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
251
252
253
254
255
256
  

      if (!mInfo.isNoAuth()) {

          if (eXosip_add_authentication_info(mSipCtx, mInfo.getSipId().c_str(), mInfo.getSipId().c_str(), mInfo.getSipPass().c_str(), NULL, mInfo.getSipRealm().c_str())) {

              LOG_ERROR("eXosip_add_authentication_info error");

              return -1;

          }

c887a0f0   Hu Chunming   提交初成版代码
257
258
259
260
261
262
263
264
265
266
267
268
      }

  

      return 0;

  }

  

  void SipServer::event_loop() {

  

      if(this->init_sip_server() !=0 ){

          return;

      }

  

      LOG_INFO("sip server init succeed:  {}:{}", mInfo.getIp(), mInfo.getPort());

c887a0f0   Hu Chunming   提交初成版代码
269
270
271
272
273
274
275
276
277
278
279
280
281
282
      

      while(!mQuit) {

          eXosip_event_t *evtp = eXosip_event_wait(mSipCtx, 0, 20);

          if (!evtp){

              eXosip_automatic_action(mSipCtx);

              osip_usleep(100000);

              continue;

          }

          eXosip_automatic_action(mSipCtx);

          this->sip_event_handle(evtp);

          eXosip_event_free(evtp);

      }

  

      mQuit = true;

c887a0f0   Hu Chunming   提交初成版代码
283
284
285
286
287
288
289
290
291
292
293
294
295
  }

  

  void SipServer::Close() {

      mQuit = true;

  

      if (m_event_loop_thread) {

          m_event_loop_thread->join();

          delete m_event_loop_thread;

          m_event_loop_thread = nullptr;

      }

      

  }

  

c887a0f0   Hu Chunming   提交初成版代码
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  void SipServer::response_message_answer(eXosip_event_t *evtp,int code){

  

      int returnCode = 0 ;

      osip_message_t * pRegister = nullptr;

      returnCode = eXosip_message_build_answer (mSipCtx,evtp->tid,code,&pRegister);

      bool bRegister = false;

      if(pRegister){

          bRegister = true;

      }

      if (returnCode == 0 && bRegister)

      {

          eXosip_lock(mSipCtx);

          eXosip_message_send_answer (mSipCtx,evtp->tid,code,pRegister);

          eXosip_unlock(mSipCtx);

      }

      else{

          LOG_ERROR("code={},returnCode={},bRegister={}",code,returnCode,bRegister);

      }

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
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
  }

  

  void SipServer::response_register_noauth(eXosip_event_t *evtp) {

      int expire = -1;

      osip_header_t* header = NULL;

      osip_message_header_get_byname(evtp->request, "expires", 0, &header);

      if (NULL != header && NULL != header->hvalue) {

          expire = atoi(header->hvalue);

      }

  

      osip_contact_t *contact = nullptr;

      osip_message_get_contact (evtp->request, 0, &contact);

      if (!(contact && contact->url)) {

          LOG_WARN("contact is null.");

          return ;

      }

  

      if (expire <= 0) {

          std::lock_guard<std::mutex> l(m_client_map_mtx);

          string sip_id = strdup(contact->url->username);

          deleteClientByDevice(sip_id);

          LOG_INFO("unregister succeed:{}", sip_id);

          return ;

      }

  

      dump_request(evtp);

c887a0f0   Hu Chunming   提交初成版代码
340
  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
341
342
      response_message_answer(evtp,200);

      cacheClient(contact->url, expire);

c887a0f0   Hu Chunming   提交初成版代码
343
  }

c887a0f0   Hu Chunming   提交初成版代码
344
  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
345
  void SipServer::response_register(eXosip_event_t *evtp) {

c887a0f0   Hu Chunming   提交初成版代码
346
  

73ef4ff3   Hu Chunming   提交三方库
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
      int expire = -1;

      osip_header_t* header = NULL;

      osip_message_header_get_byname(evtp->request, "expires", 0, &header);

      if (NULL != header && NULL != header->hvalue) {

          expire = atoi(header->hvalue);

      }

  

      osip_contact_t *contact = nullptr;

      osip_message_get_contact (evtp->request, 0, &contact);

      if (!(contact && contact->url)) {

          LOG_WARN("contact is null.");

          return ;

      }

  

      if (expire <= 0) {

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
362
          std::lock_guard<std::mutex> l(m_client_map_mtx);

73ef4ff3   Hu Chunming   提交三方库
363
364
365
366
367
368
          string sip_id = strdup(contact->url->username);

          deleteClientByDevice(sip_id);

          LOG_INFO("unregister succeed:{}", sip_id);

          return ;

      }

  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
369
370
371
372
373
      dump_request(evtp);

  

      osip_authorization_t * auth = nullptr;

      osip_message_get_authorization(evtp->request, 0, &auth);

      if(auth && auth->uri){

c887a0f0   Hu Chunming   提交初成版代码
374
375
376
377
378
379
380
381
382
  

          char *method = NULL, // REGISTER

          *algorithm = NULL, // MD5

          *username = NULL,// 340200000013200000024

          *realm = NULL, // sip服务器传给客户端,客户端携带并提交上来的sip服务域

          *nonce = NULL, //sip服务器传给客户端,客户端携带并提交上来的nonce

          *nonce_count = NULL,

          *uri = NULL; // sip:34020000002000000001@3402000000

  

c887a0f0   Hu Chunming   提交初成版代码
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
          method = evtp->request->sip_method;

          char calc_response[HASHHEXLEN];

          HASHHEX HA1, HA2 = "", Response;

  

  #define SIP_STRDUP(field) if (auth->field) (field) = osip_strdup_without_quote(auth->field)

  

          SIP_STRDUP(algorithm);

          SIP_STRDUP(username);

          SIP_STRDUP(realm);

          SIP_STRDUP(nonce);

          SIP_STRDUP(nonce_count);

          SIP_STRDUP(uri);

  

          DigestCalcHA1(algorithm, username, realm, mInfo.getSipPass().c_str(), nonce, nonce_count, HA1);

          DigestCalcResponse(HA1, nonce, nonce_count, auth->cnonce, auth->message_qop, 0, method, uri, HA2, Response);

  

          HASHHEX temp_HA1;

          HASHHEX temp_response;

          DigestCalcHA1("REGISTER", username, mInfo.getSipRealm().c_str(), mInfo.getSipPass().c_str(), mInfo.getNonce().c_str(), NULL, temp_HA1);

          DigestCalcResponse(temp_HA1, mInfo.getNonce().c_str(), NULL, NULL, NULL, 0, method, uri, NULL, temp_response);

          memcpy(calc_response, temp_response, HASHHEXLEN);

  

c887a0f0   Hu Chunming   提交初成版代码
405
406
          if (!memcmp(calc_response, Response, HASHHEXLEN)) {

              this->response_message_answer(evtp,200);

10821ac3   Hu Chunming   1.定时刷新设备目录;
407
              cacheClient(contact->url, expire);

c887a0f0   Hu Chunming   提交初成版代码
408
409
410
411
412
413
414
415
416
417
418
419
420
          } else {

              this->response_message_answer(evtp,401);

              LOG_INFO("Camera registration error, p={},port={},device={}", strdup(contact->url->host), atoi(contact->url->port), strdup(username));

          }

  

          osip_free(algorithm);

          osip_free(username);

          osip_free(realm);

          osip_free(nonce);

          osip_free(nonce_count);

          osip_free(uri);

      } else {

          response_register_401unauthorized(evtp);

10821ac3   Hu Chunming   1.定时刷新设备目录;
421
          cacheClient(contact->url, expire);

73ef4ff3   Hu Chunming   提交三方库
422
423
424
      }

  }

  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
425
426
427
428
429
430
431
432
433
434
435
436
437
438
  int SipServer::check_device_type(string sip_id) {

      if (sip_id.length() != 20) {

          LOG_ERROR("sip id error:{}", sip_id);

          return -1;

      }

      string strType = sip_id.substr(10, 3);

  

      int type = atoi(strType.c_str());

  

      LOG_DEBUG("device type: {}", type);

  

      return type;

  }

  

10821ac3   Hu Chunming   1.定时刷新设备目录;
439
  void SipServer::cacheClient(osip_uri_t *url, int expiry) {

73ef4ff3   Hu Chunming   提交三方库
440
441
442
  

      string sip_id = strdup(url->username);

  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
443
444
445
446
447
      int type = check_device_type(sip_id);

      if (-1 == type) {

          return;

      }

  

10821ac3   Hu Chunming   1.定时刷新设备目录;
448
449
      long cur_ts = Utools::get_cur_time_ms();

  

73ef4ff3   Hu Chunming   提交三方库
450
451
452
453
      // 已经注册的不再注册

      std::lock_guard<std::mutex> l(m_client_map_mtx);

      auto it = mClientMap.find(sip_id);

      if (it != mClientMap.end()) {

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
454
455
456
457
458
459
460
461
          if (cur_ts - it->second->getHeartBeat() < 5*60*1000) {

              it->second->setExpiry(expiry);

              it->second->updateHeartBeat(cur_ts);

              return ;

          } else {

              deleteClientByDevice(sip_id);

              LOG_INFO("与上次注册时间超过5分钟,重新缓存:{}", sip_id);

          }

c887a0f0   Hu Chunming   提交初成版代码
462
463
      }

  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
464
      Client* client = new Client(strdup(url->host), atoi(url->port), sip_id);

10821ac3   Hu Chunming   1.定时刷新设备目录;
465
466
      client->setExpiry(expiry);

      client->updateHeartBeat(cur_ts);

73ef4ff3   Hu Chunming   提交三方库
467
468
469
470
  

      LOG_INFO("Camera registration succee,ip={},port={},device={}",client->getIp(),client->getPort(),client->getDevice());

      

      mClientMap.insert(std::make_pair(client->getDevice(),client));

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
471
472
473
474
  

      if (type >= 111 && type <= 130) {

          // NVR注册成功,立即请求设备目录

          RequestCatalog(client);

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
475
          client->setDeviceType(DEVICE_TYPE_NVR);

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
476
477
      } else if (type >= 131 && type <= 199) {

          RequestDeviceInfo(client);

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
478
          client->setDeviceType(DEVICE_TYPE_IPC);

e975618a   Hu Chunming   1.初始化 添加是否鉴权模式的日志
479
480
      } else if (type >= 200 && type <= 299) {

          RequestCatalog(client);

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
481
          client->setDeviceType(DEVICE_TYPE_PLATFORM);

e975618a   Hu Chunming   1.初始化 添加是否鉴权模式的日志
482
      } else {

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
483
484
485
          LOG_WARN("device type is not supported:{}",type);

      }

      

c887a0f0   Hu Chunming   提交初成版代码
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
  }

  

  void SipServer::response_register_401unauthorized(eXosip_event_t *evtp) {

  

      char *dest = nullptr;

      osip_message_t * reg = nullptr;

      osip_www_authenticate_t * header = nullptr;

  

      osip_www_authenticate_init(&header);

      osip_www_authenticate_set_auth_type (header, osip_strdup("Digest"));

      osip_www_authenticate_set_realm(header,osip_enquote(mInfo.getSipRealm().c_str()));

      osip_www_authenticate_set_nonce(header,osip_enquote(mInfo.getNonce().c_str()));

      osip_www_authenticate_to_str(header, &dest);

      int ret = eXosip_message_build_answer (mSipCtx, evtp->tid, 401, &reg);

      if ( ret == 0 && reg != nullptr ) {

          osip_message_set_www_authenticate(reg, dest);

          osip_message_set_content_type(reg, "Application/MANSCDP+xml");

          eXosip_lock(mSipCtx);

          eXosip_message_send_answer (mSipCtx, evtp->tid,401, reg);

          eXosip_unlock(mSipCtx);

          LOG_INFO("response_register_401unauthorized success");

      }else {

          LOG_INFO("response_register_401unauthorized error");

      }

  

      osip_www_authenticate_free(header);

      osip_free(dest);

  

  }

  

  void printDevice(std::vector<DeviceInfo>  vec_device) {

c887a0f0   Hu Chunming   提交初成版代码
517
518
519
      for (size_t i = 0; i < vec_device.size(); i++) {

          LOG_INFO("{}   {}", vec_device[i].id, vec_device[i].parentid);

      }

c887a0f0   Hu Chunming   提交初成版代码
520
521
522
523
524
525
526
527
528
529
530
531
  }

  

  void SipServer::response_message(eXosip_event_t *evtp) {

  

      osip_body_t* body = nullptr;

      char CmdType[64] = {0};

      char DeviceID[64] = {0};

      osip_message_get_body(evtp->request, 0, &body);

      if(body){

          parse_xml(body->body, "<CmdType>", false, "</CmdType>", false, CmdType);

          parse_xml(body->body, "<DeviceID>", false, "</DeviceID>", false, DeviceID);

      }

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
532
533
534
535
      else {

          return;

      }

  

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
536
      LOG_INFO("{} - {}", CmdType, DeviceID);

c887a0f0   Hu Chunming   提交初成版代码
537
538
539
540
  

      if(!strcmp(CmdType, "Catalog")) {

          this->response_message_answer(evtp,200);

          // 需要根据对方的Catelog请求,做一些相应的应答请求

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
541
          GBXmlParser catPaser;

c887a0f0   Hu Chunming   提交初成版代码
542
543
544
545
546
547
548
549
          std::vector<DeviceInfo>  vec_device = catPaser.DecodeCatlog(body->body);

          printDevice(vec_device);

  

          std::lock_guard<std::mutex> l(m_device_map_mtx);

          for (size_t i = 0; i < vec_device.size(); i++) {

              DeviceInfo info = vec_device[i];

              m_device_map[info.id] = info;

          }

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
550
551
552
      } else if (!strcmp(CmdType, "DeviceInfo")) {

          this->response_message_answer(evtp, 200);

          // 需要根据对方的Catelog请求,做一些相应的应答请求

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
553
          GBXmlParser catPaser;

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
554
          DeviceInfo info = catPaser.DecodeDeviceInfo(body->body);

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
555
          info.status = STATUS_ON; // 有值返回就已经可以表明设备状态在线了

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
556
557
558
559
560
  

          std::lock_guard<std::mutex> l(m_device_map_mtx);

          m_device_map[info.id] = info;

  

      } else if(!strcmp(CmdType, "Keepalive")){

c887a0f0   Hu Chunming   提交初成版代码
561
          std::lock_guard<std::mutex> l_c(m_client_map_mtx);

10821ac3   Hu Chunming   1.定时刷新设备目录;
562
563
          auto it = mClientMap.find(DeviceID);

          if (it != mClientMap.end()) {

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
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
              

              Client* client = it->second;

              client->updateHeartBeat(Utools::get_cur_time_ms());

              DeviceType type = client->getDeviceType();

              if (DEVICE_TYPE_NVR == type || DEVICE_TYPE_PLATFORM == type) {

                  GBXmlParser xmlPaser;

                  vector<string> vec_id = xmlPaser.ParseKeepalive(body->body);

  

                  std::lock_guard<std::mutex> l_d(m_device_map_mtx);

                  for (auto it_device = m_device_map.begin(); it_device != m_device_map.end(); it_device++) {

                      string device_id = it_device->first;

                      bool bOff = false;

                      for (size_t i = 0; i < vec_id.size(); i++)  {

                          string dev_id = vec_id[i];

                          if (dev_id == device_id) {

                              it_device->second.status = STATUS_OFF;

                              bOff = true;

                          }

                      }

                      if (!bOff) {

                          //修正短时间offon后无法变回on的问题

                          it_device->second.status = STATUS_ON;

                      }

                      

                  }

              }

  

12040639   Hu Chunming   未注册但是发保活信息的设备,令其重新注册
591
              response_message_answer(evtp,200);

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
592
              

10821ac3   Hu Chunming   1.定时刷新设备目录;
593
              return ;

12040639   Hu Chunming   未注册但是发保活信息的设备,令其重新注册
594
595
596
          } else {

              // 未注册设备发保活信息,超过设备的最大超时次数后,设备将进行初始注册

              response_message_answer(evtp,408);

c887a0f0   Hu Chunming   提交初成版代码
597
598
599
600
601
602
603
604
605
606
607
608
609
          }

      }else{

          this->response_message_answer(evtp,200);

      }

  }

  

  bool SipServer::check_device_status(string id) {

      std::lock_guard<std::mutex> l(m_device_map_mtx);

      auto it_info = m_device_map.find(id);

      if (it_info == m_device_map.end()) {

          return false;

      }

  

756d2ef6   Hu Chunming   修改缓存设备状态的更新方式
610
611
      DeviceStatus status = it_info->second.status;

      if (STATUS_ON == status){

c887a0f0   Hu Chunming   提交初成版代码
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
          return true;

      }

      

      return false;

  }

  

  Client* SipServer::get_parent_by_id(string id) {

      std::lock_guard<std::mutex> l(m_device_map_mtx);

      auto it_info = m_device_map.find(id);

      if (it_info == m_device_map.end()) {

          return nullptr;

      }

      string parent_id = it_info->second.parentid;

  

      std::lock_guard<std::mutex> l_c(m_client_map_mtx);

      auto it_client = mClientMap.find(parent_id);

      if (it_client == mClientMap.end()) {

          return nullptr;

      }

      

      return mClientMap[parent_id];

  }

  

  void SipServer::response_invite_ack(eXosip_event_t *evtp){

  

      osip_message_t* msg = nullptr;

      int ret = eXosip_call_build_ack(mSipCtx, evtp->did, &msg);

      if (!ret && msg) {

          eXosip_call_send_ack(mSipCtx, evtp->did, msg);

      } else {

          LOG_ERROR("eXosip_call_send_ack error={}", ret);

      }

  

  }

  int SipServer::request_bye(eXosip_event_t* evtp) {

  

      eXosip_lock(mSipCtx);

      int ret = eXosip_call_terminate(mSipCtx, evtp->cid, evtp->did);

      eXosip_unlock(mSipCtx);

  

      return ret;

  }

  

  int SipServer::ByeInvite(std::string channel_id, string ip, int rtpPort) {

  

e918c2a7   Hu Chunming   call release 自动重新...
657
658
      std::lock_guard<std::mutex> l(m_invite_callinfo_map_mtx);

  

c887a0f0   Hu Chunming   提交初成版代码
659
660
661
662
663
664
665
666
667
668
      auto key = std::make_tuple(channel_id, ip, rtpPort);

  

      auto it = m_invite_callinfo_map.find(key);

      if (it == m_invite_callinfo_map.end()) {

          return -1;

      }

      

      CallInfo info = it->second;

  

      eXosip_lock(mSipCtx);

e918c2a7   Hu Chunming   call release 自动重新...
669
      eXosip_call_terminate(mSipCtx, info.cid, info.did);

c887a0f0   Hu Chunming   提交初成版代码
670
671
672
673
      eXosip_unlock(mSipCtx);

  

      m_invite_callinfo_map.erase(it);

  

e918c2a7   Hu Chunming   call release 自动重新...
674
675
676
      std::lock_guard<std::mutex> l_cmd(m_invite_cmd_map_mtx);

      m_invite_cmd_map.erase(it->first);

  

c887a0f0   Hu Chunming   提交初成版代码
677
678
679
      return 0;

  }

  

e918c2a7   Hu Chunming   call release 自动重新...
680
681
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
  int SipServer::reInvite(int cid) {

  

      std::lock_guard<std::mutex> l(m_invite_callinfo_map_mtx);

  

      bool bFound = false;

      auto it = m_invite_callinfo_map.begin();

      for (; it != m_invite_callinfo_map.end(); it++) {

          CallInfo info = it->second;

          if (info.cid == cid) {

              bFound = true;

              break;

          }

      }

      

      if (bFound)

      {

          auto key = it->first;

  

          std::lock_guard<std::mutex> l_cmd(m_invite_cmd_map_mtx);

          auto it_cmd = m_invite_cmd_map.find(key);

          if(it_cmd != m_invite_cmd_map.end()) {

              string strChannelId = std::get<0>(key);

              string strIp = std::get<1>(key);

              int iPort = std::get<2>(key);

  

              int ret = -1;

              string cmd = it_cmd->second;

              if (cmd == "udp") {

                  ret = RequestInvite_UDP(strChannelId.c_str(), strIp.c_str(), iPort);

              } else if (cmd == "tcp_a") {

                  ret = RequestInvite_TCP_a(strChannelId.c_str(), strIp.c_str(), iPort);

              }

  

              if (ret <= 0) {

                  LOG_ERROR("reInvite failed!");

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
715
                  //m_pWsServer->response_client(strChannelId, iPort, cmd, ret);

e918c2a7   Hu Chunming   call release 自动重新...
716
717
718
719
720
721
722
              }

          }

      }

      

      return -1;

  }

  

c887a0f0   Hu Chunming   提交初成版代码
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
  int SipServer::RequestInvite_UDP(const char* dst_channel, const char* rtpIp, int rtpPort) {

  

      // 检查设备是否在线

      if (!check_device_status(dst_channel)) {

          LOG_ERROR("{} is not online!", dst_channel);

          return -2;

      }

  

      Client* client = get_parent_by_id(dst_channel);

      if (client == nullptr) {

          LOG_ERROR("do not get parent device:{}", dst_channel);

          return -1;

      }

  

      LOG_INFO("INVITE UDP: {}  {}:{}", dst_channel, rtpIp, rtpPort);

  

      char session_exp[1024] = { 0 };

      osip_message_t* msg = nullptr;

      char from[1024] = { 0 };

      char to[1024] = { 0 };

      char sdp[2048] = { 0 };

  

      sprintf(from, "sip:%s@%s:%d", mInfo.getSipId().c_str(), mInfo.getIp().c_str(), mInfo.getPort());

      sprintf(to, "sip:%s@%s:%d", dst_channel, client->getIp().c_str(), client->getPort());

      snprintf(sdp, 2048,

          "v=0\r\n"

          "o=%s 0 0 IN IP4 %s\r\n"

          "s=Play\r\n"

          "c=IN IP4 %s\r\n"

          "t=0 0\r\n"

          "m=video %d RTP/AVP 96 98 97\r\n"

          "a=recvonly\r\n"

          "a=rtpmap:96 PS/90000\r\n"

          "a=rtpmap:98 H264/90000\r\n"

          "a=rtpmap:97 MPEG4/90000\r\n"

          "a=setup:passive\r\n"

          "a=connection:new\r\n"

          "y=0100000001\r\n"

          "f=\r\n", mInfo.getSipId().c_str(), rtpIp, rtpIp, rtpPort);

  

      int ret = eXosip_call_build_initial_invite(mSipCtx, &msg, to, from, nullptr, nullptr);

      if (ret) {

          LOG_ERROR("eXosip_call_build_initial_invite error: {} {} ret:{}", from, to, ret);

          return -1;

      }

  

      osip_message_set_body(msg, sdp, strlen(sdp));

      osip_message_set_content_type(msg, "application/sdp");

      snprintf(session_exp, sizeof(session_exp) - 1, "%i;refresher=uac", mInfo.getTimeout());

      osip_message_set_header(msg, "Session-Expires", session_exp);

      osip_message_set_supported(msg, "timer");

  

      int call_id = eXosip_call_send_initial_invite(mSipCtx, msg);

      if (call_id > 0) {

          LOG_INFO("eXosip_call_send_initial_invite success: call_id={}", call_id);

e918c2a7   Hu Chunming   call release 自动重新...
778
779
          auto key = std::make_tuple(string(dst_channel), string(rtpIp), rtpPort);

          m_invite_cmd_map[key] = "udp";

c887a0f0   Hu Chunming   提交初成版代码
780
781
782
783
      }

      else {

          LOG_ERROR("eXosip_call_send_initial_invite error: call_id={}", call_id);

      }

e918c2a7   Hu Chunming   call release 自动重新...
784
  

c887a0f0   Hu Chunming   提交初成版代码
785
786
787
      return call_id;

  }

  

e918c2a7   Hu Chunming   call release 自动重新...
788
  int SipServer::RequestInvite_TCP_a(const char* dst_channel, const char* rtpIp, int rtpPort) {

c887a0f0   Hu Chunming   提交初成版代码
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
      // 检查设备是否在线

      if (!check_device_status(dst_channel)) {

          return -2;

      }

  

      Client* client = get_parent_by_id(dst_channel);

      if (client == nullptr) {

          return -1;

      }

  

      LOG_INFO("INVITE TCP active");

  

      char session_exp[1024] = { 0 };

      osip_message_t* msg = nullptr;

      char from[1024] = { 0 };

      char to[1024] = { 0 };

      char sdp[2048] = { 0 };

  

      // const char* dst_channel = "34020000001320000001";

  

      sprintf(from, "sip:%s@%s:%d", mInfo.getSipId().c_str(), mInfo.getIp().c_str(), mInfo.getPort());

      sprintf(to, "sip:%s@%s:%d", dst_channel, client->getIp().c_str(), client->getPort());

      snprintf(sdp, 2048,

          "v=0\r\n"

          "o=%s 0 0 IN IP4 %s\r\n"

          "s=Play\r\n"

          "c=IN IP4 %s\r\n"

          "t=0 0\r\n"

          "m=video %d TCP/RTP/AVP 96 98 97\r\n"

          "a=recvonly\r\n"

          "a=rtpmap:96 PS/90000\r\n"

          "a=rtpmap:98 H264/90000\r\n"

          "a=rtpmap:97 MPEG4/90000\r\n"

          "a=setup:active\r\n"

          "a=connection:new\r\n"

          "y=0100000001\r\n"

          "f=\r\n", mInfo.getSipId().c_str(), mInfo.getIp().c_str(), mInfo.getIp().c_str(), rtpPort);

  

      int ret = eXosip_call_build_initial_invite(mSipCtx, &msg, to, from, nullptr, nullptr);

      if (ret) {

          LOG_ERROR("eXosip_call_build_initial_invite error: {} {} ret:{}", from, to, ret);

          return -1;

      }

  

      osip_message_set_body(msg, sdp, strlen(sdp));

      osip_message_set_content_type(msg, "application/sdp");

      snprintf(session_exp, sizeof(session_exp) - 1, "%i;refresher=uac", mInfo.getTimeout());

      osip_message_set_header(msg, "Session-Expires", session_exp);

      osip_message_set_supported(msg, "timer");

  

      int call_id = eXosip_call_send_initial_invite(mSipCtx, msg);

      if (call_id > 0) {

          LOG_INFO("eXosip_call_send_initial_invite success: call_id={}", call_id);

e918c2a7   Hu Chunming   call release 自动重新...
842
843
          auto key = std::make_tuple(string(dst_channel), string(rtpIp), rtpPort);

          m_invite_cmd_map[key] = "tcp_a";

c887a0f0   Hu Chunming   提交初成版代码
844
845
846
847
848
849
850
      }

      else {

          LOG_ERROR("eXosip_call_send_initial_invite error: call_id={}", call_id);

      }

      return call_id;

  }

  

c887a0f0   Hu Chunming   提交初成版代码
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
  void SipServer::RequestCatalog(Client* client) {

  

      eXosip_lock(mSipCtx);

  

      osip_message_t* catlog_msg = NULL;

      char to[100];/*sip:主叫用户名@被叫IP地址*/

      char from[100];/*sip:被叫IP地址:被叫IP端口*/

      char xml_body[4096];

  

      memset(to, 0, 100);

      memset(from, 0, 100);

      memset(xml_body, 0, 4096);

  

      sprintf(from, "sip:%s@%s:%d", mInfo.getSipId().c_str(), mInfo.getIp().c_str(), mInfo.getPort());

      sprintf(to, "sip:%s@%s:%d", client->getDevice().c_str(), client->getIp().c_str(), client->getPort());

      eXosip_message_build_request(mSipCtx, &catlog_msg, "MESSAGE", to, from, NULL);/*构建"MESSAGE"请求*/

  

      snprintf(xml_body, 4096,

          "<?xml version=\"1.0\"?>"

          "<Query>"

          "<CmdType>Catalog</CmdType>"

          "<SN>%d</SN>"

          "<DeviceID>%s</DeviceID>"

          "</Query>", rand() % (99999 - 10000 + 1) + 10000, client->getDevice().c_str());

  

      osip_message_set_body(catlog_msg, xml_body, strlen(xml_body));

      osip_message_set_content_type(catlog_msg, "Application/MANSCDP+xml");

      eXosip_message_send_request(mSipCtx, catlog_msg);

  

      eXosip_unlock(mSipCtx);

  }

  

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
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
912
913
  void SipServer::RequestDeviceInfo(Client* client) {

      eXosip_lock(mSipCtx);

  

      osip_message_t* catlog_msg = NULL;

      char to[100];/*sip:主叫用户名@被叫IP地址*/

      char from[100];/*sip:被叫IP地址:被叫IP端口*/

      char xml_body[4096];

  

      memset(to, 0, 100);

      memset(from, 0, 100);

      memset(xml_body, 0, 4096);

  

      sprintf(from, "sip:%s@%s:%d", mInfo.getSipId().c_str(), mInfo.getIp().c_str(), mInfo.getPort());

      sprintf(to, "sip:%s@%s:%d", client->getDevice().c_str(), client->getIp().c_str(), client->getPort());

      eXosip_message_build_request(mSipCtx, &catlog_msg, "MESSAGE", to, from, NULL);/*构建"MESSAGE"请求*/

  

      snprintf(xml_body, 4096,

          "<?xml version=\"1.0\"?>"

          "<Query>"

          "<CmdType>DeviceInfo</CmdType>"

          "<SN>%d</SN>"

          "<DeviceID>%s</DeviceID>"

          "</Query>", rand() % (99999 - 10000 + 1) + 10000, client->getDevice().c_str());

  

      osip_message_set_body(catlog_msg, xml_body, strlen(xml_body));

      osip_message_set_content_type(catlog_msg, "Application/MANSCDP+xml");

      eXosip_message_send_request(mSipCtx, catlog_msg);

  

      eXosip_unlock(mSipCtx);

  }

  

c887a0f0   Hu Chunming   提交初成版代码
914
915
916
917
918
919
920
921
922
923
924
925
  int SipServer::clearClientMap(){

      std::lock_guard<std::mutex> l(m_client_map_mtx);

      for (auto iter=mClientMap.begin(); iter!=mClientMap.end(); iter++) {

          delete iter->second;

          iter->second = nullptr;

      }

      mClientMap.clear();

  

      return 0;

  }

  

  void SipServer::deleteClientByDevice(string device) {

3a5bc7be   Hu Chunming   添加无鉴权;支持摄像头直连
926
      // std::lock_guard<std::mutex> l(m_client_map_mtx); 外部调用函数的时候注意加锁,这里去掉加锁

c887a0f0   Hu Chunming   提交初成版代码
927
928
929
930
      auto it = mClientMap.find(device);

      if (it == mClientMap.end()) {

          return ;

      }

73ef4ff3   Hu Chunming   提交三方库
931
932
933
934
935
936
937
938
939
940
941
  

      std::lock_guard<std::mutex> l_d(m_device_map_mtx);

      for (auto it_device = m_device_map.begin(); it_device != m_device_map.end(); ) {

          string parent_id = it_device->second.parentid;

          if (parent_id == device) {

              it_device = m_device_map.erase(it_device);

              continue;

          }

          it_device++;

      }

      

c887a0f0   Hu Chunming   提交初成版代码
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
      delete it->second;

      it->second = nullptr;

      mClientMap.erase(it);

  }

  

  int SipServer::parse_xml(const char *data, const char *s_mark, bool with_s_make, const char *e_mark, bool with_e_make, char *dest) {

      const char* satrt = strstr( data, s_mark );

  

      if(satrt != NULL) {

          const char* end = strstr(satrt, e_mark);

  

          if(end != NULL){

              int s_pos = with_s_make ? 0 : strlen(s_mark);

              int e_pos = with_e_make ? strlen(e_mark) : 0;

  

              strncpy( dest, satrt+s_pos, (end+e_pos) - (satrt+s_pos) );

          }

          return 0;

      }

      return -1;

  

  }

  void SipServer::dump_request(eXosip_event_t *evtp) {

      char *s = nullptr;

      size_t len;

      osip_message_to_str(evtp->request, &s, &len);

      if (s) {

e918c2a7   Hu Chunming   call release 自动重新...
969
          // LOG_INFO("\nprint request start\ntype={}\n{}\nprint request end\n",evtp->type,s);

c887a0f0   Hu Chunming   提交初成版代码
970
      }

c887a0f0   Hu Chunming   提交初成版代码
971
  }

10821ac3   Hu Chunming   1.定时刷新设备目录;
972
  

c887a0f0   Hu Chunming   提交初成版代码
973
974
975
976
977
978
  void SipServer::dump_response(eXosip_event_t *evtp) {

      char *s = nullptr;

      size_t len;

      osip_message_to_str(evtp->response, &s, &len);

      if (s)

      {

e918c2a7   Hu Chunming   call release 自动重新...
979
          // LOG_INFO("\nprint response start\ntype={}\n{}\nprint response end\n",evtp->type,s);

c887a0f0   Hu Chunming   提交初成版代码
980
      }

c887a0f0   Hu Chunming   提交初成版代码
981
  }