PJSIP Received Remote Sip Header - c++

Let's asssume we've two phone and Phone1 & Phone2 they're both has custom sip header
[Phone1] ----calling----> [Phone2] (This is onIncomingCallState for Phone2 and it can read header of Phone1)
[Phone1] <----answer---- [Phone2] (This is answer for Phone2 and it send it's header with it's CallOpParam)
[Phone1] <----OnCallState----> [Phone2] (This is on call state for both, Phone2 has Phone1's header, now Phone1 need to get Phone2's header.)
I'm writing the code at the level of PjSua2 with C++, i can see the log, Phone1 has access the value of header and when i sniff also with the wireshark i can see as well. But how can i handle it at the level of pjsua2, is there any call back or something else?

Usually there are callbacks, in the on_call_media_state. Here is some bare minimum:
void SipApp::on_call_media_state(pjsua_call_id call_id)
{
pjsua_call_info info;
pjsua_call_get_info(call_id, &info);
if (info.media_status == PJSUA_CALL_MEDIA_ACTIVE) {
//pjsua_conf_connect(0, info.conf_slot);
pjsua_conf_connect(info.conf_slot, g_recorder->getSlot());
for(int i=0; i < g_players.count(); i++) {
g_players.at(i)->setSrc(info.conf_slot);
}
g_recorder->setSrc(info.conf_slot);
g_recorder->start();
// rtsp setup - start streaming the conf to a remote IP
if(1){
if (p_rtsp->asServer()) {
p_rtsp->setSrc(0);
p_rtsp->start_streaming();
} else {
p_rtsp->setSrc(0);
p_rtsp->start_recording();
}
}
}
}
Taken from repositry https://github.com/heatblazer/asteriks-debugger/blob/master/Sip/sipapp.cpp
So can you provide more info on what exactly you are missing?

Actually, it is already implemented in the pjsua2 level.
virtual void onCallState(OnCallStatePrm &prm){
..
prm.e.body.tsxState.src.rdata.wholeMsg //this is what i want exactly.
..
}

Related

c++ - WebSocketPP multiple clients

I have problem with WebSocketPP Server. I want it to handle multiple clients.
Here is my OnOpen method:
void Server::onOpen(
Server* srv,
WSServer* ws,
websocketpp::connection_hdl& hdl)
{
ServerPlayerTracker con;
con.con = &hdl;
con.protocolVersion = 0;
con.verified = false;
con.playerID = srv->playerCount++;
con.roomID = 0;
srv->players.push_back(con);
}
But in disconnection i have problem. I cant find what player with ID disconnected. Here is my OnClose method:
void Server::onClose(
Server* srv,
WSServer* ws,
websocketpp::connection_hdl& hdl)
{
for (int i = 0; i < srv->players.size(); i++)
{
if (srv->players[i].connected)
{
if ((*srv->players[i].con).lock() == hdl.lock())
{
printf("[!] Player disconnected with ID: %d\n",
srv->players[i].playerID);
srv->players.erase(srv->players.begin() + i);
}
}
}
}
In line (*srv->players[i].con).lock() == hdl.lock() it throws exception like
'this was 0xFFFFFFFFFFFFFFF7.' in file 'memory' line 75. I think it's problem with converting weak_ptr to shared_ptr. Is there any way to fix that?
My comments seemed enough to fix the problem (see comments).
For future reference and to indicate that this problem has been answered, I have created this answer.
I'm not 100% sure what is (or is not) working in your current code, since it's quite different from the way the connections are stored and retrieved within the example code (See websocketPP github/documentation example "associative storage").
Using the example, it should be rather easy to set up a multiple client structure, in the way it was intended by the library creator.
For your specific error, I believe you're on the right track about the shared/weak pointer conversion.
Best solution would be to use the list in the way it's used in the example.
Especially interesting is the "con_list" which saves all connections.
It's a typedef of std::map<connection_hdl,connection_data,std::owner_less<conn‌​ection_hdl>> con_list; con_list m_connections; and should enable you to store and retrieve connections (and their session data).

How to download a file in C++\wxWidgets

How may I download a file in C++ with wxWidgets?
Been googling and everything and nothing shows up! Help appreciated!
Use wxHTTP class for that.
wxHTTP Example Code:
#include <wx/sstream.h>
#include <wx/protocol/http.h>
wxHTTP get;
get.SetHeader(_T("Content-type"), _T("text/html; charset=utf-8"));
get.SetTimeout(10); // 10 seconds of timeout instead of 10 minutes ...
while (!get.Connect(_T("www.google.com")))
wxSleep(5);
wxApp::IsMainLoopRunning();
wxInputStream *httpStream = get.GetInputStream(_T("/intl/en/about.html"));
if (get.GetError() == wxPROTO_NOERR)
{
wxString res;
wxStringOutputStream out_stream(&res);
httpStream->Read(out_stream);
wxMessageBox(res);
}
else
{
wxMessageBox(_T("Unable to connect!"));
}
wxDELETE(httpStream);
get.Close();
If you want more flexible solution consider using libcurl.
Depends on where you want to 'download' it from, and how the file server allows files to be downloaded. The server might use FTP, or HTTP, or something more obscure. There is no way to tell from your question which has no useful information in it.
In general, I would not use wxWidgets for this task. wxWidgets is a GUI frmaework, with some extras for various things that may or may not be helpful in your case.
From HTTP as Andrejs suggest, from FTP using wxFTP
wxFTP ftp;
// if you don't use these lines anonymous login will be used
ftp.SetUser("user");
ftp.SetPassword("password");
if ( !ftp.Connect("ftp.wxwindows.org") )
{
wxLogError("Couldn't connect");
return;
}
ftp.ChDir("/pub");
wxInputStream *in = ftp.GetInputStream("wxWidgets-4.2.0.tar.gz");
if ( !in )
{
wxLogError("Coudln't get file");
}
else
{
size_t size = in->GetSize();
char *data = new char[size];
if ( !in->Read(data, size) )
{
wxLogError("Read error");
}
else
{
// file data is in the buffer
...
}
delete [] data;
delete in;
}
http://docs.wxwidgets.org/stable/wx_wxftp.html#wxftp
You did not define what "downloading a file" means to you.
If you want to use HTTP to retrieve some content, you should use an HTTP client library like libcurl and issue the appropriate HTTP GET request.

Download a single .txt using QFtp

I've got a problem with QFtp. I wanna download a single .txt file with a single line(8 bytes) from my server, so I've written the following code, but it doesn't work.
The file "actions.txt" were created in the folder1 directory. I can see the size of it pretty well in the client-side. But the file is not being written. I'm getting an empty file.
QFile* actionFile = new QFile("action.txt");
QFtp *ftp = new QFtp(parent);
void Dialog::getActionFile()
{
actionFile->open(QIODevice::WriteOnly);
ftp->connectToHost("mydomain.de");
ftp->login("user", "pw");
ftp->cd("folder1");
ftp->get("action.txt",actionFile);
ftp->close();
actionFile->close();
}
Thanks in advance.
The documentation of several methods of QFtp says:
The function does not block and returns immediately. The command is
scheduled, and its execution is performed asynchronously. The function
returns a unique identifier which is passed by commandStarted() and
commandFinished().
So you need to wait for the appropriate signals to be emitted.
Note that you can also use QNetworkRequest to request the whole ftp URL (I think even with username and password inside the URL) to download the file.
I solved my problem.
I treated one step each time the commandFininshed signal was emitted.
like this:
void MainWindow::ftpCommandFinished(int id, bool error)
{
static bool flag = false;
if(ftp->currentCommand() == QFtp::ConnectToHost)
checkUpdate();
if(ftp->currentCommand() == QFtp::Get)
{
file->close();
if(error)
{
QMessageBox::warning(this, "Erro!", ftp->errorString());
deleteLater();
return;
}
if(!flag)
checkVersion();
else{
delete ftp, file;
ftp = 0; file = 0;
}
flag = true;
}
}
the reason of the flag variable is something else that needs further explanations about the program, so i won't go down that road.
Thanks for you help. It somehow helped me a lot.

TCP Library is bundling messages?

I'm using a TCP library with a Server and Client class called Lacewing http://lacewing-project.org/
I have noticed that when I send a client several separate messages, it sometimes bundles them and the only way I can separate them is by parsing them again. When sending binary data, it is very hard to parse though.
Does anyone know why it might do this? I tried the DisableNagling() on both client and server but it still does it.
Here is an example of something I might send:
void ServerCore::loginRequestC( const std::string& userName, const std::string& password )
{
std::cout << "Got request" << std::endl;
ServerPlayer* player = (ServerPlayer*)getServerClient()->Tag;
player->setUsername(userName);
for (size_t i = 0; i < m_players.size(); ++i)
{
if(m_players[i] != player)
{
std::cout << "Telling new about " << m_players[i]->getUsername() << std::endl;
m_enc.playerJoinedS(m_players[i]->getUsername());
player->getClient()->Send(m_enc.getLastMessage().c_str());
}
}
m_enc.loginResultS(true,"");
player->getClient()->Send(m_enc.getLastMessage().c_str());
m_enc.playerJoinedS(userName);
for (size_t i = 0; i < m_players.size(); ++i)
{
if(m_players[i] != player)
m_players[i]->getClient()->Send(m_enc.getLastMessage().c_str());
}
}
So if I intended to have:
MSG_A
MSG_B
MSG_C
It might send:
MSG_A
MSG_BMSG_C
The messages get randomly bundled together. It is not my code that is the problem. I have checked.
Although it is useful to bundle messages, I want to control when it happens, not the library.
Thanks
This is not the library, but the TCP protocol itself that is doing it. TCP socket is a bi-directional stream of bytes. One write might result in multiple reads on the other side, and vise versa.
You have to design you application-level protocol so that it's easy to split that stream into messages. Common approaches are to use a length prefix or a message delimiter.
TCP is stream oriented protocol, thus it has no build in message boundaries. You will need to split the stream to messages by yourself.
UDP in opposite is datagram protocol and each packet has a separate message. A disadvantage is that it's not reliable.

Losing characters in TCP Telnet transmission

I'm using Winsock to send commands through Telnet ; but for some reason when I try to send a string, a few characters get dropped occasionally. I use send:
int SendData(const string & text)
{
send(hSocket,text.c_str(),static_cast<int>(text.size()),0);
Sleep(100);
send(hSocket,"\r",1,0);
Sleep(100);
return 0;
}
Any suggestions?
Update:
I checked and the error still occurs even if all the characters are sent. So I decided to change the Send function so that it sends individual characters and checks if they have been sent:
void SafeSend(const string &text)
{
char char_text[1];
for(size_t i = 0; i <text.size(); ++i)
{
char_text[0] = text[i];
while(send(hSocket,char_text,1,0) != 1);
}
}
Also, it drops characters in a peculiar way ; i.e. in the middle of the sentence. E.g.
set variable [fp]exit_flag = true
is sent as
ariable [fp]exit_flag = true
Or
set variable [fp]app_flag = true
is sent as
setrable [fp]app_flag = true
As mentioned in the comments you absolutely need to check the return value of send as it can return after sending only a part of your buffer.
You nearly always want to call send in a loop similar to the following (not tested as I don't have a Windows development environment available at the moment):
bool SendString(const std::string& text) {
int remaining = text.length();
const char* buf = text.data();
while (remaining > 0) {
int sent = send(hSocket, buf, remaining, 0);
if (sent == SOCKET_ERROR) {
/* Error occurred check WSAGetLastError() */
return false;
}
remaining -= sent;
buf += sent;
}
return true;
}
Update:
This is not relevant for the OP, but calls to recv should also structured in the same way as above.
To debug the problem further, Wireshark (or equivalent software) is excellent in tracking down the source of the problem.
Filter the packets you want to look at (it has lots of options) and check if they include what you think they include.
Also note that telnet is a protocol with numerous RFCs. Most of the time you can get away with just sending raw text, but it's not really guaranteed to work.
You mention that the windows telnet client sends different bytes from you, capture a minimal sequence from both clients and compare them. Use the RFCs to figure out what the other client does different and why. You can use "View -> Packet Bytes" to bring up the data of the packet and can easily inspect and copy/paste the hex dump.