summaryrefslogtreecommitdiff
path: root/Bus/Ivy/IvyApplication.cxx
blob: c4de0754c745c2c9b28efa2578ee09bb90113d23 (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
// IvyApplication.cpp : implementation file
//

#include "IvyStdAfx.h"

#include "IvyApplication.h"



//#define IVY_DEBUG

#define ARG_START 2
#define ARG_END 3

static char * firstArg( char *s, const char separator )
{
	char *ptr = s;
		
	while ( *ptr && *ptr != separator )
		ptr++;
	if ( *ptr == separator )
		return ptr++ ;  
	else  return NULL;
}
/*
function like strok but do not eat consecutive separator
*/
static char * nextArg( char **s, const char separator )
{
	char *start = *s;
	char *end = *s;
		
	while ( *end && *end != separator )
		end++;
	if ( *end == separator ) *end++ = '\0';  
	if ( end == start ) return NULL;
	*s = end;
	return start;
}
/////////////////////////////////////////////////////////////////////////////
// IvyApplication

IvyApplication::IvyApplication(Ivy * bus)
{
	this->bus = bus;
	remoteService = 0;		/* unknown or unconnected application */
	appname = "Unknown";
	AppConnectedCallbackCalled = false;
}

IvyApplication::~IvyApplication()
{
//	bus->RemoveApplication( this );
	for ( unsigned int i = 0; i < regexp_in.size(); i++)
#ifdef USE_PCRE
		pcre_free( regexp_in[i] );
#else
		delete regexp_in[i];
#endif
	regexp_in.clear();
	if ( m_hSocket != INVALID_SOCKET ) 
		Close();
}


/////////////////////////////////////////////////////////////////////////////
// IvyApplication member functions


void IvyApplication::Create(const char* host, UINT & port, const char* name)
{
	appname = name;
	// Exception to catch
	CBufferedSocket::Create();
	Connect(host, port);
}



UINT IvyApplication::Create()
{
	ivy::string host;
	UINT port;
	CBufferedSocket::Create();
	// Max Listen Connexion 
	Listen( SOMAXCONN );
	GetSockName( host, port );
	TRACE(" TCP %s:%d\n", host.c_str(), port );
#ifdef IVY_DEBUG
	TRACE( "IvyApplication::Create server socket %d\n", m_hSocket );
#endif
	return port;
}

void IvyApplication::OnReceive(char * line)
{
	int err;
	unsigned int id;
	int kind_of_msg = Bye;
    char *arg;
	int argc = 0;
	char *arg_ptr;

#ifdef USE_PCRE
	pcre *exp;
	const char *argv[max_subexp];
	const char *errmsg;
	int erroffset;
#else
	Regexp *exp;
    const char *argv[Regexp::NSUBEXP];
#endif


#ifdef IVY_DEBUG
	TRACE("Receive %s\n",line);
#endif //IVY_DEBUG

	err = sscanf_s( line ,"%d %d", &kind_of_msg, &id);
	arg = firstArg( line , ARG_START );
	if ( (err != 2) || (arg == NULL) )
		{
		TRACE("Quitting bad format  %s\n",  line);
		SendMsg(Error, Error, "bad format request expected 'type id ...'");
//		bus->RemoveApplication( this );
		Close();
		return;
		}
	arg++;
	switch( kind_of_msg )
		{
		case Bye:

#ifdef IVY_DEBUG
				TRACE("Quitting  %s\n",  line);
#endif //IVY_DEBUG

//			bus->RemoveApplication( this );
			OnClose(0);
			//Close();
			break;
		case Error:

#ifdef IVY_DEBUG
				TRACE("Receive error %d  %s\n",  id, arg);
#endif //IVY_DEBUG

			break;
		case AddRegexp:

#ifdef IVY_DEBUG
				TRACE("Regexp  id=%d exp='%s'\n",  id, arg);
#endif //IVY_DEBUG

			if ( !bus->CheckRegexp( arg ) )
				{
#ifdef IVY_DEBUG
				TRACE("Warning exp='%s' can't match removing from %s\n",arg,appname.c_str());
#endif //IVY_DEBUG
				return;
				}
#ifdef USE_PCRE
			exp = pcre_compile( arg, PCRE_CASELESS, &errmsg, &erroffset, NULL );
			if ( !exp )
			{
				ivy::string errstr( "Error can't compile regexp '" );
				errstr += arg;
				errstr += "' error ";
				errstr += errmsg;
				SendMsg( Error, Error,  errstr.c_str() );
				TRACE("IvyApplication %s\n",errstr.c_str());
				return;
			}
#else
			exp = new Regexp( arg );
			if ( !exp->CompiledOK() )
				{
				ivy::string err( "Error can't compile regexp '" );
				err += arg;
				err += "' error ";
				err += exp->GetErrorString();
				SendMsg( Error, Error,  err.c_str() );
				TRACE("IvyApplication %s\n",err.c_str());
				return;
				}
#endif
			if ( regexp_in.size() < (id + 1) )
				regexp_in.resize( id + 1 );
			regexp_in[ id ] =  exp;
#ifdef IVY_DEBUG
				TRACE("Adding regexp[%d]='%s' size: %d\n",id,arg,regexp_in.size());
#endif //IVY_DEBUG
			break;
		case DelRegexp:

#ifdef IVY_DEBUG
				TRACE("Regexp Delete id=%d\n",  id);
#endif //IVY_DEBUG
			if ( regexp_in[id]  )
			{
			exp = regexp_in[ id ];
#ifdef USE_PCRE
			pcre_free( exp );
#else
			delete exp;
#endif
			regexp_in[ id ] = NULL;
			}
			break;
		case StartRegexp:

#ifdef IVY_DEBUG
				TRACE("Regexp Start id=%d\n",  id);
#endif //IVY_DEBUG

			appname = arg;
			/* remote socket port */
			remoteService = id;
			if ( bus->CheckConnected( this ) )
			{
			TRACE("Quitting already connected  %s\n",  appname.c_str());
			SendMsg( Error, Error,  "already connected" );
//			bus->RemoveApplication( this );
			Close();
			}
			break;
		case EndRegexp:

#ifdef IVY_DEBUG
				TRACE("Regexp End id=%d\n",  id);
#endif //IVY_DEBUG
			
			bus->CallApplicationConnectedCallback( this );
			AppConnectedCallbackCalled = true;
			if ( !bus->ready_message.empty() )
				SendMsg( bus->ready_message.c_str() );
			break;
		case Msg:

#ifdef IVY_DEBUG
				TRACE("Message id=%d msg='%s'\n", id, arg);
#endif //IVY_DEBUG

			arg_ptr = arg;
			arg = nextArg( &arg_ptr, ARG_END);
			while ( arg )
				{
				argv[argc++] = arg;
				arg = nextArg( &arg_ptr, ARG_END );
				}
			bus->CallMessageCallback( this, id, argc, argv );
			break;
		case DirectMsg:

#ifdef IVY_DEBUG
				TRACE("Direct Message id=%d msg='%s'\n", id, arg);
#endif //IVY_DEBUG

			bus->CallDirectMessageCallback( this, id, arg );
			break;
		case Die:

#ifdef IVY_DEBUG
			TRACE("Die Message id=%d msg='%s'\n", id, arg);
#endif //IVY_DEBUG

			if ( bus->CallDieCallback( this, id, arg ) )
			{
			PostMessage( NULL, WM_CLOSE, 0, 0);
			exit(-1);
			}
			break;

		default:
			TRACE("Receive unhandled message %s\n",  line);
			break;
		}
}


void IvyApplication::SendMsg(MsgType msg, int id, const char * arg)
{
	char buffer[1024];
	if ( arg )
		_snprintf_s( buffer, sizeof( buffer ),sizeof( buffer )-1, "%d %d%c%s\n", msg, id, ARG_START, arg );
		else sprintf_s( buffer,sizeof( buffer ), "%d %d%c\n", msg, id, ARG_START);

#ifdef IVY_DEBUG
	TRACE("SendMsg %s\n",buffer);
#endif //IVY_DEBUG
	Send( buffer );
}

void IvyApplication::OnAccept(int nErrorCode) 
{
	ivy::string remotehost;
	UINT remoteport;
	
	// construct a new, empty socket

	IvyApplication *newapp = new IvyApplication(bus);

	// accept connection

	Accept( *newapp );
	newapp->GetPeerName( remotehost, remoteport );
	TRACE("Connexion de %s:%u\n", remotehost.c_str(), remoteport );
	bus->AddApplication( newapp );
}

void IvyApplication::OnClose(int nErrorCode) 
{
	ivy::string remotehost;
	UINT remoteport;
	GetPeerName( remotehost, remoteport );
	TRACE("Deconnexion de %s:%u\n", remotehost.c_str(), remoteport );
	if ( AppConnectedCallbackCalled )
				bus->CallApplicationDisconnectedCallback( this );

	for ( unsigned int i = 0; i < regexp_in.size(); i++)
#ifdef USE_PCRE
		pcre_free( regexp_in[i] );
#else
		delete regexp_in[i];
#endif
	regexp_in.clear();
	Close();
	//bus->RemoveApplication( this );
}

int IvyApplication::SendMsg(const char *message)
{
	int count = 0;
#ifdef USE_PCRE
	pcre *exp;
	int ovector[max_subexp*3];
#else
	Regexp *exp;
#endif
	/* send to already connected */
	for ( unsigned int i  = 0; i < regexp_in.size(); i++ )
	{
		exp = regexp_in[i];
#ifdef USE_PCRE
		int match_count = pcre_exec( exp, NULL, message, (int) strlen( message ), 0, 0, ovector, max_subexp );
		if ( match_count > 0 )
		{
			ivy::string buffer;
			const char **substring;
			int err = pcre_get_substring_list(message,ovector, match_count, &substring);
			if ( err != 0 )
			{
				SendMsg( Error, Error, "Memory Alloc Error" );
			}
			else {
			for ( int j = 1; j < match_count; j++ )
				{
				buffer += substring[j];
				buffer += ARG_END;
				}
			pcre_free_substring_list(substring);
			SendMsg( Msg, i, buffer.c_str() );
			count++;
			}
		}
#else
		if ( exp && exp->Match( message ) )
			{
			ivy::string buffer;
			for ( int j = 1; j < exp->SubStrings()+1; j++ )
				{
				buffer += (*exp)[j];
				buffer += ARG_END;
				}
			SendMsg( Msg, i, buffer.c_str() );
			count++;
			}
#endif
	}
	return count;
}

const char *IvyApplication::GetName(void)
{
return appname.c_str();
}


BOOL IvyApplication::SameApplication(IvyApplication * app)
{
 ivy::string host1;
 UINT port1;
 ivy::string host2;
 UINT port2;
 if ( (remoteService != 0) && (remoteService == app->remoteService) )
	{
	GetPeerName( host1, port1 );
	app->GetPeerName( host2, port2 );
	TRACE( "IvyApplication::SameApplication %s:%d %s:%d\n", host1.c_str(),port1, host2.c_str(),port2);
	return ( host1 == host2  );
	}
 return false;
}