summaryrefslogtreecommitdiffstats
path: root/lskat/lskat/KRemoteConnect.cpp
blob: 315d2a9622b3f6ac1db557ceff7e84c9f16838ef (plain)
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
/***************************************************************************
                          KRemoteConnect.cpp  -  description
                             -------------------
    begin                : Tue May 2 2000
    copyright            : (C) 2000 by Martin Heni
    email                : martin@heni-online.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
/***************************************************************************
                          FILENAME|  -  description
                             -------------------
    begin                : Tue Apr 4 2000
    copyright            : (C) |1995-2000 by Martin Heni
    email                : martin@heni-online.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "KRemoteConnect.h"

#include "KRemoteConnect.moc"

const char* LSKAT_SERVICE = "_lskat._tcp";

KRemoteConnect::KRemoteConnect()
  : KChildConnect()
{
  port=7687;
  IP="localhost";
  socketStatus=KR_INVALID;
  kSocket=0;
  service=0;
  kServerSocket=0;
  bufferMsg=0;
  buffer=new char[4097];
  inputbuffer="";
  input_pending=false;
}
KRemoteConnect::~KRemoteConnect()
{
  Exit();
  delete buffer;
  delete service;
  printf("DESTGRUCTING KRemoteConenct\n");
}

KR_STATUS KRemoteConnect::QueryStatus()
{
  return socketStatus;
}

bool KRemoteConnect::Init(int id,KEMessage *msg)
{
short prt;
char *p;
int size;
bool tryserver;

  SetID(id);
  if (msg)
  {
    if (msg->GetData(TQCString("Port"),prt))
    {
      port=(unsigned int)prt;
      msg->Remove(TQCString("Port"));
    }
    if (msg->GetData(TQCString("IP"),p,size))
    {
      IP=TQCString(p);
      msg->Remove(TQCString("IP"));
    }
    if (msg->GetData(TQCString("Name"),p,size))
    {
      Name=TQString::fromUtf8(p);
      msg->Remove(TQCString("Name"));
    }
  }
  /*
  printf("Connecting to %s %u (remain=%d)\n",
      (const char *)IP,port,msg->QueryNumberOfKeys());
  */

  // First try to connect to given host:socket
  // if no IP given only offer server
  tryserver=false;
  if (!IP.isEmpty())
  {
    kSocket=new KSocket(IP.latin1(),port);
    if (!kSocket) return false;
    if (kSocket->socket()!=-1) // success
    {
      kSocket->enableRead(TRUE);
      //kSocket->enableWrite(TRUE);
      connect(kSocket,TQT_SIGNAL(closeEvent(KSocket *)),
            this,TQT_SLOT(socketClosed(KSocket *)));
      connect(kSocket,TQT_SIGNAL(readEvent(KSocket *)),
            this,TQT_SLOT(socketRead(KSocket *)));
      /*
      connect(kSocket,TQT_SIGNAL(writeEvent(KSocket *)),
            this,TQT_SLOT(socketWrite(KSocket *)));
      */
      /*
      printf("Socket(%d) %p connection built to a server\n",
              kSocket->socket(),kSocket);
      */
      socketStatus=KR_CLIENT;

      // Send msg if any
      if (msg->QueryNumberOfKeys()>0)
      {
        msg->AddData(TQCString("Server"),(short)QueryID());
        SendMsg(msg);
      }

    }
    else
    {
      tryserver=true;
    }
  }
  else
  {
    printf("NO IP given..only server possible\n");
    tryserver=true;
  }

  if (tryserver) // become a server
  {
    delete kSocket;
    kSocket=0;
    delete service;
    service = 0;
    // Store message
    if (msg->QueryNumberOfKeys()>0)
    {
      bufferMsg=new KEMessage;
      *bufferMsg=*msg;
    }
    else
    {
      bufferMsg=0;
    }
    socketStatus=KR_WAIT_FOR_CLIENT;
    OfferServerSocket();
    return false;
  }

  return true;
}

bool KRemoteConnect::OfferServerSocket()
{
  if (kServerSocket)
  {
    return false;
  }
  kServerSocket=new KRServerSocket(port,SO_REUSEADDR);
  if (!kServerSocket)
  {
    socketStatus=KR_INVALID;
    return false;
  }
  if (kServerSocket->socket()==-1)
  {
    socketStatus=KR_NO_SOCKET;
    return false;
  }
  printf("Offering socket and publishing stuff\n");
  service = new DNSSD::PublicService(Name,LSKAT_SERVICE,port);
  service->publishAsync();
  connect(kServerSocket,TQT_SIGNAL(accepted(KSocket *)),
        this,TQT_SLOT(socketRequest(KSocket *)));

  return true;
}
void KRemoteConnect::socketRequest(KSocket *sock)
{
  if (kSocket) // already connected
  {
    delete sock;
    delete kServerSocket;
    kServerSocket=0;
    return ;
  }
  kSocket=sock;
  if (kSocket->socket()!=-1) // success
  {
    kSocket->enableRead(TRUE);
    //kSocket->enableWrite(TRUE);
    connect(kSocket,TQT_SIGNAL(closeEvent(KSocket *)),
          this,TQT_SLOT(socketClosed(KSocket *)));
    connect(kSocket,TQT_SIGNAL(readEvent(KSocket *)),
          this,TQT_SLOT(socketRead(KSocket *)));
    /*
    connect(kSocket,TQT_SIGNAL(writeEvent(KSocket *)),
          this,TQT_SLOT(socketWrite(KSocket *)));
    */
    socketStatus=KR_SERVER;
    delete kServerSocket; // no more connections
    kServerSocket=0;
    if (bufferMsg)
    {
      // Delayed sending of init msg
      bufferMsg->AddData(TQCString("Client"),(short)QueryID());
      SendMsg(bufferMsg);
      delete bufferMsg;
      bufferMsg=0;
    }
  }
}

void KRemoteConnect::socketClosed(KSocket *sock)
{
  delete sock;
  kSocket=0;
  socketStatus=KR_INVALID;
  KEMessage *msg=new KEMessage;
  msg->AddData(TQCString("ConnectionLost"),(short)QueryID());
  emit signalReceiveMsg(msg,QueryID());
  delete msg;
}
void KRemoteConnect::socketRead(KSocket *sock)
{
  ssize_t buflen;
  TQString s;
  char c;
  int pos;

  // printf("++++++ Incoming socket read +++++++\n");
  if (-1==sock->socket()) return ;
  // printf("Read input on socket %p\n",sock);
  buflen=read(sock->socket(),buffer,4096);
  buffer[buflen]=0;
  // printf("Read %d byte  <%s>\n",buflen,buffer);

  if (buflen<1) return ;
  if (buffer[buflen-1]!=0) // shit..we got a not null terminated string
  {
    c=buffer[buflen-1];
    buffer[buflen-1]=0;
    s=buffer;
    s+=c;
  }
  else
  {
    s=buffer;
  }

  // Append old unresolved input
  s=inputbuffer+s;
  pos=s.findRev(KEMESSAGE_CR);
  // printf("String '%s' pos=%d len=%d\n",(const char *)s,pos,s.length());
  if (pos<0)
  {
    inputbuffer=s;
  }
  else if (pos+KEMESSAGE_CR.length()==s.length())
  {
    // CR at the end...calling receive
    Receive(s);
  }
  else
  {
    inputbuffer=s.right(s.length()-pos-KEMESSAGE_CR.length());
    s=s.left(pos+KEMESSAGE_CR.length());
    // printf("s='%s' in='%s'\n",(const char *)s,(const char *)inputbuffer);
    Receive(s);
  }
}


void KRemoteConnect::socketWrite(KSocket *)
{
 // printf("wrtie input on socket %p\n",sock);
}

bool KRemoteConnect::Exit()
{
  delete kSocket;
  delete kServerSocket;
  delete bufferMsg;
  kSocket=0;
  kServerSocket=0;
  bufferMsg=0;
  socketStatus=KR_INVALID;
  return true;
}
bool KRemoteConnect::Next()
{
  bool result;
  // printf("+- KRemoteConnect::Next() status=%d\n",socketStatus);
  if (socketStatus<=0) return false;
  // create and send message
  KEMessage *msg=new KEMessage;
  // User fills message
  emit signalPrepareMove(msg,KG_INPUTTYPE_REMOTE);
  result=SendMsg(msg);
  delete msg;
  return result;
}

// Send string to child
bool KRemoteConnect::Send(TQString str)
{
  // connected?
  if (!kSocket || kSocket->socket()==-1) return false;
  if (socketStatus<=0) return false;

  if (-1==write(kSocket->socket(),str.latin1(),str.length()+1))
  {
     printf("Warning: Problems writing to socket.\n");
     return false;
  }
  return true;;
}