aboutsummaryrefslogtreecommitdiff
path: root/src/IvyClient.java
blob: 8aad19905f4d0c906196aa9217442d5b0f10be31 (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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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
/**
 * A private Class for the the peers on the bus.
 *
 * @author	Yannick Jestin
 * @author	<a href="http://www.tls.cena.fr/products/ivy/">http://www.tls.cena.fr/products/ivy/</a>
 *
 * each time a connexion is made with a remote peer, the regexp are exchanged
 * once ready, a ready message is sent, and then we can send messages, 
 * die messages, direct messages, add or remove regexps, or quit. A thread is
 * created for each remote client.
 *
 *  CHANGELOG:
 *  1.2.3:
 *  - silently stops on InterruptedIOException.
 *  - direct Messages
 *  - deals with early stops during readline
 *  1.2.2:
 *  - cleared a bug causing the CPU to be eating when a remote client left the
 *    bus. closes Damien Figarol bug reported on december, 2002. It is handled
 *    in the readline() thread
 *  1.2.1:
 *  - removes a NullPointerException when stops pinging on a pinger that
 *    wasn't even started
 *  1.0.12:
 *  - introducing a Ping and Pong in the protocol, in order to detect the loss of
 *    connection faster. Enabled through the use of -DIVY_PING variable only
 *    the PINGTIMEOUT value in milliseconds allows me to have a status of the
 *    socket guaranteed after this timeout
 *  - right handling of IOExceptions in sendBuffer, the Client is removed from
 *    the bus
 *  - sendDie goes public, so does sendDie(String)
 *  - appName visibility changed from private to protected
 *  1.0.10:
 *  - removed the timeout bug eating all the CPU resources
 */
package fr.dgac.ivy ;
import java.lang.Thread;
import java.net.*;
import java.io.*;
import java.util.*;
import gnu.regexp.*;

public class IvyClient implements Runnable {
    
  /* the protocol magic numbers */
  final static int Bye = 0;	/* end of the peer */
  final static int AddRegexp = 1;/* the peer adds a regexp */
  final static int Msg = 2 ;	/* the peer sends a message */
  final static int Error = 3; 	/* error message */
  final static int DelRegexp = 4;/* the peer removes one of his regex */
  final static int EndRegexp = 5;/* no more regexp in the handshake */
  final static int SchizoToken = 6; /* avoid race condition in concurrent connexions */
  final static int DirectMsg = 7;/* the peer sends a direct message */
  final static int Die = 8;  /* the peer wants us to quit */
  final static int Ping = 9;  /* checks the presence of the other */
  final static int Pong = 10;  /* checks the presence of the other */

  final static String MESSAGE_TERMINATOR = "\n"; /* the next protocol will use \r */
  final static String StartArg = "\u0002";/* begin of arguments */
  final static String EndArg = "\u0003"; /* end of arguments */


  private static boolean debug = (System.getProperty("IVY_DEBUG")!=null) ;
  private Ivy bus;
  private Socket socket;
  private BufferedReader in;
  private OutputStream out;
  private Hashtable regexp_in = new Hashtable();
  private Hashtable regexp_text = new Hashtable();
  private int appPort;
  private boolean peerCalling;
  private volatile Thread clientThread;// volatile to ensure the quick communication
  private Integer clientKey ;
  private static boolean doping = (System.getProperty("IVY_PING")!=null) ;
  final static int PINGTIMEOUT = 5000; 
  private PINGER pinger;
  private volatile Thread pingerThread;

  // protected variables
  String appName;

  IvyClient(Ivy bus, Socket socket,boolean peerCalling,Integer clientKey) throws IOException {
    appName = "Unknown";
    appPort = 0;
    this.bus = bus;
    this.socket = socket;
    this.peerCalling=peerCalling;
    this.clientKey=clientKey;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = socket.getOutputStream();
    Hashtable regexps=bus.regexp_out;
    // sends our ID, whether we initiated the connexion or not
    // the ID is the couple "host name,application Port", the host name
    // information is in the socket itself, the port is not known if we
    // initiate the connexion
    send(SchizoToken,bus.applicationPort,bus.appName);
    // sends our regexps to the peer
    for (Enumeration e = regexps.keys(); e.hasMoreElements(); ) {
      Integer ikey = (Integer)e.nextElement();
      sendRegexp( ikey.intValue(),(String)regexps.get(ikey));
    }
    send( EndRegexp,0,"");
    // spawns a thread to manage the incoming traffic on this
    // socket. We should be ready to receive messages now.
    clientThread = new Thread(this);
    clientThread .start();
    if (doping) {
      pinger = new PINGER();
      pingerThread=new Thread(pinger);
      pingerThread.start();
    }
  }

  /**
   *  returns the name of the remote agent.
   */
  public String getApplicationName() { return appName ; }

  Integer getClientKey() { return clientKey ; }

  /**
   *  allow an Ivy package class to access the list of regexps at a
   *  given time.
   *  perhaps we should implement a new IvyApplicationListener method to
   *  allow the notification of regexp addition and deletion
   */
  Enumeration getRegexps() { return regexp_text.elements(); }

  int getAppPort() { return appPort ; }

  void sendRegexp(int id,String regexp) {
    send(AddRegexp,id,regexp); /* perhaps we should perform some checking here */
  }

  public void delRegexp(int id) {send( DelRegexp,id,"");}

  /**
   * sends a direct message to the peer
   * @param id the numeric value provided to the remote client
   * @param message the string that will be match-tested
   */
  public void sendDirectMsg(int id,String message) { send(DirectMsg,id,message); }
  
  /**
   * closes the connexion to the peer.
   * @param notify should I send Bye message ?
   * the thread managing the socket is stopped
   */
  void close(boolean notify) throws IOException {
    traceDebug("closing connexion to "+appName);
    if (doping&&(pinger!=null)) { pinger.stopPinging(); }
    if (notify) sendBye("hasta la vista");
    stopListening();
    // bus.clientDisconnect(this);
    socket.close();  // should I also close in and out ?
  }

  /**
   * sends the substrings of a message to the peer for each matching regexp.
   * @param message the string that will be match-tested
   * @return the number of messages sent to the peer
   */
  int sendMsg( String message ) {
    int count = 0;
    for (Enumeration e = regexp_in.keys();e.hasMoreElements();) {
      Integer key = (Integer)e.nextElement();
      RE regexp = (RE)regexp_in.get(key);
      REMatch result = regexp.getMatch(message);
      if ( result != null ) {
        send(Msg,key,regexp.getNumSubs(),result);
	count++;
      }
    }
    return count;
  }
  
  void stopListening() {
    Thread t = clientThread;
    if (t==null) return; // we can be summoned to quit from two path at a time
    clientThread=null;
    t.interrupt();
  }

  /**
   * compares two peers the id is the couple (host,service port).
   * @param clnt the other peer
   * @return true if the peers are similir. This should not happen, it is bad
   * © ® (tm)
   */
  boolean sameClient( IvyClient clnt ) {
    return ( appPort != 0 && appPort == clnt.appPort )
      && ( getRemoteAddress() == clnt.getRemoteAddress() ) ;
  }

  /**
   * the code of the thread handling the incoming messages.
   */
  public void run() {
    Thread thisThread = Thread.currentThread();
    String msg = null;
    try {
      traceDebug("Connected from "+ socket.getInetAddress().getHostName()+ ":"+socket.getPort());
    } catch (Exception ie) {
      traceDebug("Interrupted while resolving remote hostname");
    }
    traceDebug("Thread started");
    while (clientThread==thisThread) {
      try {
	if ((msg=in.readLine()) != null ) {
	  if (clientThread!=thisThread) break; // early stop during readLine()
	  if (doping && (pingerThread!=null)) pingerThread.interrupt();
	  newParseMsg(msg);
	} else {
	  traceDebug("readline null ! leaving the thead");
	  break;
	}
      } catch (IvyException ie) {
	ie.printStackTrace();
      } catch (InterruptedIOException ioe) {
	traceDebug("I have been interrupted. I'm about to leave my thread loop");
	if (thisThread!=clientThread) break;
      } catch (IOException e) {
	traceDebug("abnormally Disconnected from "+ socket.getInetAddress().getHostName()+":"+socket.getPort());
	break;
      }
    }
    traceDebug("normally Disconnected from "+ appName);
    traceDebug("Thread stopped");
  }

  private void sendBuffer( String buffer ) throws IvyException {
    buffer += "\n";
    try {
      out.write(buffer.getBytes() );
      out.flush();
    } catch ( IOException e ) {
      traceDebug("I can't send my message to this client. He probably left");
      // first, I'm not a first class IvyClient any more
      bus.removeClient(this);
      // invokes the die applicationListeners
      bus.disconnectReceived(this);
      try {
        close(false);
      } catch (IOException ioe) {
	throw new IvyException("close failed"+ioe.getMessage());
      }
    }
  }

  private void send(int type, int id, String arg) {
    try {
      sendBuffer(type+" "+id+StartArg+arg);
    } catch (IvyException ie ) {
      System.err.println("received an exception: " + ie.getMessage());
      ie.printStackTrace();
    }
  }

  private void send(int type, Integer id, int nbsub, REMatch result) {
    String buffer = type+" "+id+StartArg;
    // Start at 1 because group 0 represent entire matching
    for(int sub = 1; sub <= nbsub; sub++) {
      if (result.getStartIndex(sub) > -1) {
	buffer += result.toString(sub)+EndArg;
      }
    }
    try {
      sendBuffer(buffer);
    } catch (IvyException ie ) {
      System.err.println("received an exception: " + ie.getMessage());
      ie.printStackTrace();
    }
  }

  private String dumpHex(String s) {
    byte[] b = s.getBytes();
    String out = "";
    String zu = "\t";
    for (int i=0;i<b.length;i++) {
      char c = s.charAt(i);
      out+=((int)c) + " ";
      zu+= ((c>15) ? c : 'X')+" ";
    }
    out += zu;
    return out;
  }

  private String dumpMsg(String s) {
    String deb = " \""+s+"\" "+s.length()+" cars, ";
    for (int i=0;i<s.length();i++) {
      deb+= "["+s.charAt(i) + "]:" + (int)s.charAt(i) +", ";
    }
    return s;
  }

  private void newParseMsg(String s) throws IvyException {
    byte[] b = s.getBytes();
    int from=0,to=0,msgType;
    Integer msgId;
    while ((to<b.length)&&(b[to]!=' ')) to++;
    if (to>=b.length) throw new IvyException("protocol error");
    try {
      msgType = Integer.parseInt(s.substring(from,to));
    } catch (NumberFormatException nfe) {
      throw new IvyException("protocol error on msgType");
    }
    from=to+1;
    while ((to<b.length)&&(b[to]!=2)) to++;
    if (to>=b.length) throw new IvyException("protocol error");
    try {
      msgId = new Integer(s.substring(from,to));
    } catch (NumberFormatException nfe) {
      throw new IvyException("protocol error on identifier");
    }
    from=to+1;
    switch (msgType) {
      case Die:
	traceDebug("received die Message from " + appName);
	// first, I'm not a first class IvyClient any more
	bus.removeClient(this);
	// invokes the die applicationListeners
	bus.dieReceived(this,msgId.intValue());
	// makes the bus die
	bus.stop();
	try {
	  close(false);
	} catch (IOException ioe) {
	  throw new IvyException(ioe.getMessage());
	}
	break;
      case Bye:
	// the peer quits
	traceDebug("received bye Message from "+appName);
	// first, I'm not a first class IvyClient any more
	bus.removeClient(this);
	// invokes the die applicationListeners
	bus.disconnectReceived(this);
	try {
	  close(false);
	} catch (IOException ioe) {
	  throw new IvyException(ioe.getMessage());
	}
	break;
      case AddRegexp:
	String regexp=s.substring(from,b.length);
	if ( bus.CheckRegexp(regexp) ) {
	  try {
	    regexp_in.put(msgId,new RE(regexp));
	    regexp_text.put(msgId,regexp);
	  } catch (REException e) {
	    throw new IvyException("regexp error " +e.getMessage());
	  }
	} else {
	  throw new IvyException("regexp Warning exp='"+regexp+"' can't match removing from "+appName);
	}
	break;
      case DelRegexp:
	regexp_in.remove(msgId);
	regexp_text.remove(msgId);
	break;
      case EndRegexp:
	bus.connect(this);
	/* 
	 * the peer is perhaps not ready to handle this message
	 * an assymetric processing should be written
	 */
	if (bus.ready_message!=null) sendMsg(bus.ready_message);
	break;
      case Msg:
	Vector v = new Vector();
	while (to<b.length) {
	  while ( (to<b.length) && (b[to]!=3) ) to++;
	  if (to<b.length) {
	    v.addElement(s.substring(from,to));
	    to++;
	    from=to;
	  }
	}
	String[] tab = new String[v.size()];
	for (int i=0;i<v.size();i++) {
	  tab[i]=(String)v.elementAt(i);
	  // for developpemnt purposes
	  // System.out.println(" *"+tab[i]+"* "+(tab[i]).length());
	}
	bus.callCallback(this,msgId,tab);
	break;
      case Pong:
	String paramPong=s.substring(from,b.length);
	traceDebug("Ping msg from "+appName+" : "+paramPong);
	break;
      case Ping:
	// I receive a ping. I can answer a pong.
	String param=s.substring(from,b.length);
	traceDebug("Ping msg from "+appName+" : "+param);
	sendPong(param);
	break;
      case Error:
	String error=s.substring(from,b.length);
	traceDebug("Error msg "+msgId+" "+error);
  	break;
      case SchizoToken:
	appName=s.substring(from,b.length);
	appPort=msgId.intValue();
	if ( bus.checkConnected(this) ) {
	  try  {
	    close(false);
	  } catch (IOException ioe) {
	  throw new IvyException("io " + ioe.getMessage());
	  }
	  throw new IvyException("Rare ! A concurrent connect occured");
	}
	break;
      case DirectMsg: 
	String direct=s.substring(from,b.length);
	bus.directMessage( this, msgId.intValue(), direct );
	break;
      default:
        throw new IvyException("protocol error, unknown message type "+msgType);
    }
  }

  void sendPong(String s) {send(Pong,0,s);}
  void sendPing(String s) {send(Ping,0,s);}

  private void sendBye() {send(Bye,0,"");}
  private void sendBye(String message) {send(Bye,0,message);}
  
  public void sendDie() { send(Die,0,""); }
  public void sendDie(String message) {send(Die,0,message);}

  private InetAddress getRemoteAddress() { return socket.getInetAddress(); }

  public String toString() {
    return "IvyClient "+bus.appName+":"+appName;
  }

  private void traceDebug(String s){
    if (debug) System.out.println("-->IvyClient "+bus.appName+":"+appName+"<-- "+s);
  }

  class PINGER implements Runnable {
    boolean isPinging = false;
    public void run() {
      isPinging=true;
      traceDebug("Pinger Thread started");
      while (isPinging) {
	try {
	  Thread.sleep(PINGTIMEOUT);
	  sendPing("are you here ?");
	} catch (InterruptedException ie) {
	}
      }
      traceDebug("Pinger Thread stopped");
    }
    public void stopPinging() { isPinging=false; pingerThread.interrupt();}
  }

}