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
|
/*
This file is part of the KDE games library
Copyright (C) 2001 Burkhard Lehner (Burkhard.Lehner@gmx.de)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
/*
KMessageIO class and subclasses KMessageSocket and KMessageDirect
*/
#include "kmessageio.h"
#include <QTcpSocket>
#include <KProcess>
#include <QFile>
#include <QDataStream>
// ----------------------- KMessageIO -------------------------
KMessageIO::KMessageIO (QObject *parent)
: QObject (parent), m_id (0)
{
}
KMessageIO::~KMessageIO ()
{}
void KMessageIO::setId (quint32 id)
{
m_id = id;
}
quint32 KMessageIO::id ()
{
return m_id;
}
// ----------------------KMessageSocket -----------------------
KMessageSocket::KMessageSocket (const QString& host, quint16 port, QObject *parent)
: KMessageIO (parent)
{
mSocket = new QTcpSocket ();
mSocket->connectToHost (host, port);
initSocket ();
}
KMessageSocket::KMessageSocket (const QHostAddress &host, quint16 port, QObject *parent)
: KMessageIO (parent)
{
mSocket = new QTcpSocket ();
mSocket->connectToHost (host.toString(), port);
initSocket ();
}
KMessageSocket::KMessageSocket (QTcpSocket *socket, QObject *parent)
: KMessageIO (parent)
{
mSocket = socket;
initSocket ();
}
KMessageSocket::KMessageSocket (int socketFD, QObject *parent)
: KMessageIO (parent)
{
mSocket = new QTcpSocket ();
mSocket->setSocketDescriptor (socketFD);
initSocket ();
}
KMessageSocket::~KMessageSocket ()
{
delete mSocket;
}
bool KMessageSocket::isConnected () const
{
return mSocket->state() == QAbstractSocket::ConnectedState;
}
void KMessageSocket::send (const QByteArray &msg)
{
QDataStream str (mSocket);
str << quint8 ('M'); // magic number for begin of message
str.writeBytes (msg.data(), msg.size()); // writes the length (as quint32) and the data
}
void KMessageSocket::processNewData ()
{
if (isRecursive)
return;
isRecursive = true;
QDataStream str (mSocket);
while (mSocket->bytesAvailable() > 0)
{
if (mAwaitingHeader)
{
// Header = magic number + packet length = 5 bytes
if (mSocket->bytesAvailable() < 5)
{
isRecursive = false;
return;
}
// Read the magic number first. If something unexpected is found,
// start over again, ignoring the data that was read up to then.
quint8 v;
str >> v;
if (v != 'M')
{
qCWarning(GAMES_PRIVATE_KGAME) << ": Received unexpected data, magic number wrong!";
continue;
}
str >> mNextBlockLength;
mAwaitingHeader = false;
}
else
{
// Data not completely read => wait for more
if (mSocket->bytesAvailable() < (qint64) mNextBlockLength)
{
isRecursive = false;
return;
}
QByteArray msg (mNextBlockLength, 0);
str.readRawData (msg.data(), mNextBlockLength);
// send the received message
Q_EMIT received (msg);
// Waiting for the header of the next message
mAwaitingHeader = true;
}
}
isRecursive = false;
}
void KMessageSocket::initSocket ()
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(mSocket, &QTcpSocket::errorOccurred,
#else
connect(mSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
#endif
this, &KMessageSocket::connectionBroken);
connect(mSocket, &QTcpSocket::disconnected, this, &KMessageSocket::connectionBroken);
connect(mSocket, &QTcpSocket::readyRead, this, &KMessageSocket::processNewData);
mAwaitingHeader = true;
mNextBlockLength = 0;
isRecursive = false;
}
quint16 KMessageSocket::peerPort () const
{
return mSocket->peerPort();
}
QString KMessageSocket::peerName () const
{
return mSocket->peerName();
}
// ----------------------KMessageDirect -----------------------
KMessageDirect::KMessageDirect (KMessageDirect *partner, QObject *parent)
: KMessageIO (parent), mPartner (nullptr)
{
// 0 as first parameter leaves the object unconnected
if (!partner)
return;
// Check if the other object is already connected
if (partner && partner->mPartner)
{
qCWarning(GAMES_PRIVATE_KGAME) << ": Object is already connected!";
return;
}
// Connect from us to that object
mPartner = partner;
// Connect the other object to us
partner->mPartner = this;
}
KMessageDirect::~KMessageDirect ()
{
if (mPartner)
{
mPartner->mPartner = nullptr;
Q_EMIT mPartner->connectionBroken();
}
}
bool KMessageDirect::isConnected () const
{
return mPartner != nullptr;
}
void KMessageDirect::send (const QByteArray &msg)
{
if (mPartner)
Q_EMIT mPartner->received (msg);
else
qCCritical(GAMES_PRIVATE_KGAME) << ": Not yet connected!";
}
// ----------------------- KMessageProcess ---------------------------
KMessageProcess::~KMessageProcess()
{
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess::Delete process";
if (mProcess)
{
mProcess->kill();
mProcess->deleteLater();
mProcess=nullptr;
// Maybe todo: delete mSendBuffer
}
}
KMessageProcess::KMessageProcess(QObject *parent, const QString& file) : KMessageIO(parent)
{
// Start process
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess::Start process";
mProcessName=file;
mProcess=new KProcess;
// Need both stdout and stderr as separate channels in the communication
mProcess-> setOutputChannelMode(KProcess::SeparateChannels);
int id=0;
*mProcess << mProcessName << QStringLiteral( "%1").arg(id);
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess::Init:Id=" << id;
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessgeProcess::Init:Processname:" << mProcessName;
connect(mProcess, &KProcess::readyReadStandardOutput, this, &KMessageProcess::slotReceivedStdout);
connect(mProcess, &KProcess::readyReadStandardError, this, &KMessageProcess::slotReceivedStderr);
connect(mProcess, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), this, &KMessageProcess::slotProcessExited);
mProcess->start();
mSendBuffer=nullptr;
mReceiveCount=0;
mReceiveBuffer.resize(1024);
}
bool KMessageProcess::isConnected() const
{
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess::Is connected";
if (!mProcess)
return false;
return (mProcess->state() == QProcess::Running);
}
// Send to process
void KMessageProcess::send(const QByteArray &msg)
{
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess:: SEND("<<msg.size()<<") to process";
unsigned int size=msg.size()+2*sizeof(long);
if (mProcess == nullptr) {
qCDebug(GAMES_PRIVATE_KGAME) << "@@@KMessageProcess:: cannot write to stdin, no process available";
return;
}
char *tmpbuffer=new char[size];
long *p1=(long *)tmpbuffer;
long *p2=p1+1;
qCDebug(GAMES_PRIVATE_KGAME) << "p1="<<p1 << "p2="<< p2;
memcpy(tmpbuffer+2*sizeof(long),msg.data(),msg.size());
*p1=0x4242aeae;
*p2=size;
// no need to add it to a queue -> qiodevice is buffered
mProcess->write(tmpbuffer,size);
delete [] tmpbuffer;
}
void KMessageProcess::slotReceivedStderr()
{
QByteArray ba;
qCDebug(GAMES_PRIVATE_KGAME)<<"@@@ KMessageProcess::slotReceivedStderr";
mProcess->setReadChannel(QProcess::StandardError);
while(mProcess->canReadLine())
{
ba = mProcess->readLine();
if( ba.isEmpty() )
return;
ba.chop( 1 ); // remove QLatin1Char( '\n' )
qCDebug(GAMES_PRIVATE_KGAME) << "KProcess (" << ba.size() << "):" << ba.constData();
Q_EMIT signalReceivedStderr(QLatin1String( ba ));
ba.clear();
};
}
void KMessageProcess::slotReceivedStdout()
{
mProcess->setReadChannel(QProcess::StandardOutput);
QByteArray ba = mProcess->readAll();
qCDebug(GAMES_PRIVATE_KGAME) << "$$$$$$ " << ": Received" << ba.size() << "bytes over inter process communication";
// Resize receive buffer
while (mReceiveCount+ba.size()>=mReceiveBuffer.size()) mReceiveBuffer.resize(mReceiveBuffer.size()+1024);
// was 08/2007: mReceiveBuffer += ba;
std::copy(ba.begin(), ba.begin()+ba.size(), mReceiveBuffer.begin()+mReceiveCount);
mReceiveCount += ba.size();
// Possible message
while (mReceiveCount>int(2*sizeof(long)))
{
long *p1=(long *)mReceiveBuffer.data();
long *p2=p1+1;
int len;
if (*p1!=0x4242aeae)
{
qCDebug(GAMES_PRIVATE_KGAME) << ": Cookie error...transmission failure...serious problem...";
}
len=(int)(*p2);
if (len<int(2*sizeof(long)))
{
qCDebug(GAMES_PRIVATE_KGAME) << ": Message size error";
break;
}
if (len<=mReceiveCount)
{
qCDebug(GAMES_PRIVATE_KGAME) << ": Got message with len" << len;
QByteArray msg ;
msg.resize(len);
// msg.setRawData(mReceiveBuffer.data()+2*sizeof(long),len-2*sizeof(long));
std::copy(mReceiveBuffer.begin()+2*sizeof(long),mReceiveBuffer.begin()+len, msg.begin());
// msg.duplicate(mReceiveBuffer.data()+2*sizeof(long),len-2*sizeof(long));
Q_EMIT received(msg);
// msg.resetRawData(mReceiveBuffer.data()+2*sizeof(long),len-2*sizeof(long));
// Shift buffer
if (len<mReceiveCount)
{
memmove(mReceiveBuffer.data(),mReceiveBuffer.data()+len,mReceiveCount-len);
}
mReceiveCount-=len;
}
else break;
}
}
void KMessageProcess::slotProcessExited(int exitCode, QProcess::ExitStatus)
{
qCDebug(GAMES_PRIVATE_KGAME) << "Process exited (slot) with code" << exitCode;
Q_EMIT connectionBroken();
delete mProcess;
mProcess=nullptr;
}
|