]> git.saurik.com Git - wxWidgets.git/blob - src/common/sckipc.cpp
new wxASSERT implementation using wxAssert() helper function
[wxWidgets.git] / src / common / sckipc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: sckipc.cpp
3 // Purpose: Interprocess communication implementation (wxSocket version)
4 // Author: Julian Smart
5 // Modified by: Guilhem Lavaux (big rewrite) May 1997, 1998
6 // Guillermo Rodriguez (updated for wxSocket v2) Jan 2000
7 // (callbacks deprecated) Mar 2000
8 // Vadim Zeitlin (added support for Unix sockets) Apr 2002
9 // Created: 1993
10 // RCS-ID: $Id$
11 // Copyright: (c) Julian Smart 1993
12 // (c) Guilhem Lavaux 1997, 1998
13 // (c) 2000 Guillermo Rodriguez <guille@iies.es>
14 // Licence: wxWindows license
15 /////////////////////////////////////////////////////////////////////////////
16
17 // ==========================================================================
18 // declarations
19 // ==========================================================================
20
21 // --------------------------------------------------------------------------
22 // headers
23 // --------------------------------------------------------------------------
24
25 #ifdef __GNUG__
26 #pragma implementation "sckipc.h"
27 #endif
28
29 // For compilers that support precompilation, includes "wx.h".
30 #include "wx/wxprec.h"
31
32 #ifdef __BORLANDC__
33 #pragma hdrstop
34 #endif
35
36 #ifndef WX_PRECOMP
37 #include "wx/log.h"
38 #endif
39
40 #if wxUSE_SOCKETS && wxUSE_IPC && wxUSE_STREAMS
41
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <errno.h>
45
46 #include "wx/socket.h"
47 #include "wx/sckipc.h"
48 #include "wx/module.h"
49 #include "wx/event.h"
50
51 // --------------------------------------------------------------------------
52 // macros and constants
53 // --------------------------------------------------------------------------
54
55 // It seems to be already defined somewhere in the Xt includes.
56 #ifndef __XT__
57 // Message codes
58 enum
59 {
60 IPC_EXECUTE = 1,
61 IPC_REQUEST,
62 IPC_POKE,
63 IPC_ADVISE_START,
64 IPC_ADVISE_REQUEST,
65 IPC_ADVISE,
66 IPC_ADVISE_STOP,
67 IPC_REQUEST_REPLY,
68 IPC_FAIL,
69 IPC_CONNECT,
70 IPC_DISCONNECT
71 };
72 #endif
73
74 // All sockets will be created with the following flags
75 #define SCKIPC_FLAGS (wxSOCKET_WAITALL)
76
77 // headers needed for umask()
78 #ifdef __UNIX_LIKE__
79 #include <sys/types.h>
80 #include <sys/stat.h>
81 #endif // __UNIX_LIKE__
82
83 // ----------------------------------------------------------------------------
84 // private functions
85 // ----------------------------------------------------------------------------
86
87 // get the address object for the given server name, the caller must delete it
88 static wxSockAddress *
89 GetAddressFromName(const wxString& serverName, const wxString& host = _T(""))
90 {
91 // we always use INET sockets under non-Unix systems
92 #if defined(__UNIX__) && !defined(__WXMAC__)
93 // under Unix, if the server name looks like a path, create a AF_UNIX
94 // socket instead of AF_INET one
95 if ( serverName.Find(_T('/')) != wxNOT_FOUND )
96 {
97 wxUNIXaddress *addr = new wxUNIXaddress;
98 addr->Filename(serverName);
99
100 return addr;
101 }
102 #endif // Unix/!Unix
103 {
104 wxIPV4address *addr = new wxIPV4address;
105 addr->Service(serverName);
106 if ( !host.empty() )
107 {
108 addr->Hostname(host);
109 }
110
111 return addr;
112 }
113 }
114
115 // --------------------------------------------------------------------------
116 // wxTCPEventHandler stuff (private class)
117 // --------------------------------------------------------------------------
118
119 class wxTCPEventHandler : public wxEvtHandler
120 {
121 public:
122 wxTCPEventHandler() : wxEvtHandler() {};
123
124 void Client_OnRequest(wxSocketEvent& event);
125 void Server_OnRequest(wxSocketEvent& event);
126
127 DECLARE_EVENT_TABLE()
128 };
129
130 enum
131 {
132 _CLIENT_ONREQUEST_ID = 1000,
133 _SERVER_ONREQUEST_ID
134 };
135
136 static wxTCPEventHandler *gs_handler = NULL;
137
138 // ==========================================================================
139 // implementation
140 // ==========================================================================
141
142 IMPLEMENT_DYNAMIC_CLASS(wxTCPServer, wxServerBase)
143 IMPLEMENT_DYNAMIC_CLASS(wxTCPClient, wxClientBase)
144 IMPLEMENT_CLASS(wxTCPConnection, wxConnectionBase)
145
146 // --------------------------------------------------------------------------
147 // wxTCPClient
148 // --------------------------------------------------------------------------
149
150 wxTCPClient::wxTCPClient () : wxClientBase()
151 {
152 }
153
154 wxTCPClient::~wxTCPClient ()
155 {
156 }
157
158 bool wxTCPClient::ValidHost(const wxString& host)
159 {
160 wxIPV4address addr;
161
162 return addr.Hostname(host);
163 }
164
165 wxConnectionBase *wxTCPClient::MakeConnection (const wxString& host,
166 const wxString& serverName,
167 const wxString& topic)
168 {
169 wxSocketClient *client = new wxSocketClient(SCKIPC_FLAGS);
170 wxSocketStream *stream = new wxSocketStream(*client);
171 wxDataInputStream *data_is = new wxDataInputStream(*stream);
172 wxDataOutputStream *data_os = new wxDataOutputStream(*stream);
173
174 wxSockAddress *addr = GetAddressFromName(serverName, host);
175 if ( !addr )
176 return NULL;
177
178 bool ok = client->Connect(*addr);
179 delete addr;
180
181 if ( ok )
182 {
183 unsigned char msg;
184
185 // Send topic name, and enquire whether this has succeeded
186 data_os->Write8(IPC_CONNECT);
187 data_os->WriteString(topic);
188
189 msg = data_is->Read8();
190
191 // OK! Confirmation.
192 if (msg == IPC_CONNECT)
193 {
194 wxTCPConnection *connection = (wxTCPConnection *)OnMakeConnection ();
195
196 if (connection)
197 {
198 if (connection->IsKindOf(CLASSINFO(wxTCPConnection)))
199 {
200 connection->m_topic = topic;
201 connection->m_sock = client;
202 connection->m_sockstrm = stream;
203 connection->m_codeci = data_is;
204 connection->m_codeco = data_os;
205 client->SetEventHandler(*gs_handler, _CLIENT_ONREQUEST_ID);
206 client->SetClientData(connection);
207 client->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
208 client->Notify(TRUE);
209 return connection;
210 }
211 else
212 {
213 delete connection;
214 // and fall through to delete everything else
215 }
216 }
217 }
218 }
219
220 // Something went wrong, delete everything
221 delete data_is;
222 delete data_os;
223 delete stream;
224 client->Destroy();
225
226 return NULL;
227 }
228
229 wxConnectionBase *wxTCPClient::OnMakeConnection()
230 {
231 return new wxTCPConnection();
232 }
233
234 // --------------------------------------------------------------------------
235 // wxTCPServer
236 // --------------------------------------------------------------------------
237
238 wxTCPServer::wxTCPServer () : wxServerBase()
239 {
240 m_server = NULL;
241 }
242
243 bool wxTCPServer::Create(const wxString& serverName)
244 {
245 // Destroy previous server, if any
246 if (m_server)
247 {
248 m_server->SetClientData(NULL);
249 m_server->Destroy();
250 m_server = NULL;
251 }
252
253 wxSockAddress *addr = GetAddressFromName(serverName);
254 if ( !addr )
255 return FALSE;
256
257 #ifdef __UNIX_LIKE__
258 mode_t umaskOld;
259 if ( addr->Type() == wxSockAddress::UNIX )
260 {
261 // ensure that the file doesn't exist as otherwise calling socket() would
262 // fail
263 int rc = remove(serverName);
264 if ( rc < 0 && errno != ENOENT )
265 {
266 delete addr;
267
268 return FALSE;
269 }
270
271 // also set the umask to prevent the others from reading our file
272 umaskOld = umask(077);
273 }
274 else
275 {
276 // unused anyhow but shut down the compiler warnings
277 umaskOld = 0;
278 }
279 #endif // __UNIX_LIKE__
280
281 // Create a socket listening on the specified port
282 m_server = new wxSocketServer(*addr, SCKIPC_FLAGS);
283
284 #ifdef __UNIX_LIKE__
285 if ( addr->Type() == wxSockAddress::UNIX )
286 {
287 // restore the umask
288 umask(umaskOld);
289
290 // save the file name to remove it later
291 m_filename = serverName;
292 }
293 #endif // __UNIX_LIKE__
294
295 delete addr;
296
297 if (!m_server->Ok())
298 {
299 m_server->Destroy();
300 m_server = NULL;
301
302 return FALSE;
303 }
304
305 m_server->SetEventHandler(*gs_handler, _SERVER_ONREQUEST_ID);
306 m_server->SetClientData(this);
307 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
308 m_server->Notify(TRUE);
309
310 return TRUE;
311 }
312
313 wxTCPServer::~wxTCPServer()
314 {
315 if (m_server)
316 {
317 m_server->SetClientData(NULL);
318 m_server->Destroy();
319 }
320
321 #ifdef __UNIX_LIKE__
322 if ( !m_filename.empty() )
323 {
324 if ( remove(m_filename) != 0 )
325 {
326 wxLogDebug(_T("Stale AF_UNIX file '%s' left."), m_filename.c_str());
327 }
328 }
329 #endif // __UNIX_LIKE__
330 }
331
332 wxConnectionBase *wxTCPServer::OnAcceptConnection( const wxString& WXUNUSED(topic) )
333 {
334 return new wxTCPConnection();
335 }
336
337 // --------------------------------------------------------------------------
338 // wxTCPConnection
339 // --------------------------------------------------------------------------
340
341 wxTCPConnection::wxTCPConnection () : wxConnectionBase()
342 {
343 m_sock = NULL;
344 m_sockstrm = NULL;
345 m_codeci = NULL;
346 m_codeco = NULL;
347 }
348
349 wxTCPConnection::wxTCPConnection(char * WXUNUSED(buffer), int WXUNUSED(size))
350 {
351 }
352
353 wxTCPConnection::~wxTCPConnection ()
354 {
355 wxDELETE(m_codeci);
356 wxDELETE(m_codeco);
357 wxDELETE(m_sockstrm);
358
359 if (m_sock)
360 {
361 m_sock->SetClientData(NULL);
362 m_sock->Destroy();
363 }
364 }
365
366 void wxTCPConnection::Compress(bool WXUNUSED(on))
367 {
368 // Use wxLZWStream
369 }
370
371 // Calls that CLIENT can make.
372 bool wxTCPConnection::Disconnect ()
373 {
374 // Send the the disconnect message to the peer.
375 m_codeco->Write8(IPC_DISCONNECT);
376 m_sock->Notify(FALSE);
377 m_sock->Close();
378
379 return TRUE;
380 }
381
382 bool wxTCPConnection::Execute(const wxChar *data, int size, wxIPCFormat format)
383 {
384 if (!m_sock->IsConnected())
385 return FALSE;
386
387 // Prepare EXECUTE message
388 m_codeco->Write8(IPC_EXECUTE);
389 m_codeco->Write8(format);
390
391 if (size < 0)
392 size = wxStrlen(data) + 1; // includes final NUL
393
394 m_codeco->Write32(size);
395 m_sockstrm->Write(data, size);
396
397 return TRUE;
398 }
399
400 char *wxTCPConnection::Request (const wxString& item, int *size, wxIPCFormat format)
401 {
402 if (!m_sock->IsConnected())
403 return NULL;
404
405 m_codeco->Write8(IPC_REQUEST);
406 m_codeco->WriteString(item);
407 m_codeco->Write8(format);
408
409 // If Unpack doesn't initialize it.
410 int ret;
411
412 ret = m_codeci->Read8();
413 if (ret == IPC_FAIL)
414 return NULL;
415 else
416 {
417 size_t s;
418 char *data = NULL;
419
420 s = m_codeci->Read32();
421 data = new char[s];
422 m_sockstrm->Read(data, s);
423
424 if (size)
425 *size = s;
426 return data;
427 }
428 }
429
430 bool wxTCPConnection::Poke (const wxString& item, wxChar *data, int size, wxIPCFormat format)
431 {
432 if (!m_sock->IsConnected())
433 return FALSE;
434
435 m_codeco->Write8(IPC_POKE);
436 m_codeco->WriteString(item);
437 m_codeco->Write8(format);
438
439 if (size < 0)
440 size = wxStrlen(data) + 1; // includes final NUL
441
442 m_codeco->Write32(size);
443 m_sockstrm->Write(data, size);
444
445 return TRUE;
446 }
447
448 bool wxTCPConnection::StartAdvise (const wxString& item)
449 {
450 int ret;
451
452 if (!m_sock->IsConnected())
453 return FALSE;
454
455 m_codeco->Write8(IPC_ADVISE_START);
456 m_codeco->WriteString(item);
457
458 ret = m_codeci->Read8();
459
460 if (ret != IPC_FAIL)
461 return TRUE;
462 else
463 return FALSE;
464 }
465
466 bool wxTCPConnection::StopAdvise (const wxString& item)
467 {
468 int msg;
469
470 if (!m_sock->IsConnected())
471 return FALSE;
472
473 m_codeco->Write8(IPC_ADVISE_STOP);
474 m_codeco->WriteString(item);
475
476 msg = m_codeci->Read8();
477
478 if (msg != IPC_FAIL)
479 return TRUE;
480 else
481 return FALSE;
482 }
483
484 // Calls that SERVER can make
485 bool wxTCPConnection::Advise (const wxString& item,
486 wxChar *data, int size, wxIPCFormat format)
487 {
488 if (!m_sock->IsConnected())
489 return FALSE;
490
491 m_codeco->Write8(IPC_ADVISE);
492 m_codeco->WriteString(item);
493 m_codeco->Write8(format);
494
495 if (size < 0)
496 size = wxStrlen(data) + 1; // includes final NUL
497
498 m_codeco->Write32(size);
499 m_sockstrm->Write(data, size);
500
501 return TRUE;
502 }
503
504 // --------------------------------------------------------------------------
505 // wxTCPEventHandler (private class)
506 // --------------------------------------------------------------------------
507
508 BEGIN_EVENT_TABLE(wxTCPEventHandler, wxEvtHandler)
509 EVT_SOCKET(_CLIENT_ONREQUEST_ID, wxTCPEventHandler::Client_OnRequest)
510 EVT_SOCKET(_SERVER_ONREQUEST_ID, wxTCPEventHandler::Server_OnRequest)
511 END_EVENT_TABLE()
512
513 void wxTCPEventHandler::Client_OnRequest(wxSocketEvent &event)
514 {
515 wxSocketBase *sock = event.GetSocket();
516 wxSocketNotify evt = event.GetSocketEvent();
517 wxTCPConnection *connection = (wxTCPConnection *)(sock->GetClientData());
518
519 // This socket is being deleted; skip this event
520 if (!connection)
521 return;
522
523 int msg = 0;
524 wxDataInputStream *codeci;
525 wxDataOutputStream *codeco;
526 wxSocketStream *sockstrm;
527 wxString topic_name = connection->m_topic;
528 wxString item;
529
530 // We lost the connection: destroy everything
531 if (evt == wxSOCKET_LOST)
532 {
533 sock->Notify(FALSE);
534 sock->Close();
535 connection->OnDisconnect();
536 return;
537 }
538
539 // Receive message number.
540 codeci = connection->m_codeci;
541 codeco = connection->m_codeco;
542 sockstrm = connection->m_sockstrm;
543 msg = codeci->Read8();
544
545 switch (msg)
546 {
547 case IPC_EXECUTE:
548 {
549 char *data;
550 size_t size;
551 wxIPCFormat format;
552
553 format = (wxIPCFormat)codeci->Read8();
554 size = codeci->Read32();
555 data = new char[size];
556 sockstrm->Read(data, size);
557
558 connection->OnExecute (topic_name, data, size, format);
559
560 delete [] data;
561 break;
562 }
563 case IPC_ADVISE:
564 {
565 char *data;
566 size_t size;
567 wxIPCFormat format;
568
569 item = codeci->ReadString();
570 format = (wxIPCFormat)codeci->Read8();
571 size = codeci->Read32();
572 data = new char[size];
573 sockstrm->Read(data, size);
574
575 connection->OnAdvise (topic_name, item, data, size, format);
576
577 delete [] data;
578 break;
579 }
580 case IPC_ADVISE_START:
581 {
582 item = codeci->ReadString();
583
584 bool ok = connection->OnStartAdvise (topic_name, item);
585 if (ok)
586 codeco->Write8(IPC_ADVISE_START);
587 else
588 codeco->Write8(IPC_FAIL);
589
590 break;
591 }
592 case IPC_ADVISE_STOP:
593 {
594 item = codeci->ReadString();
595
596 bool ok = connection->OnStopAdvise (topic_name, item);
597 if (ok)
598 codeco->Write8(IPC_ADVISE_STOP);
599 else
600 codeco->Write8(IPC_FAIL);
601
602 break;
603 }
604 case IPC_POKE:
605 {
606 wxIPCFormat format;
607 size_t size;
608 wxChar *data;
609
610 item = codeci->ReadString();
611 format = (wxIPCFormat)codeci->Read8();
612 size = codeci->Read32();
613 data = new wxChar[size];
614 sockstrm->Read(data, size);
615
616 connection->OnPoke (topic_name, item, data, size, format);
617
618 delete [] data;
619
620 break;
621 }
622 case IPC_REQUEST:
623 {
624 wxIPCFormat format;
625
626 item = codeci->ReadString();
627 format = (wxIPCFormat)codeci->Read8();
628
629 int user_size = -1;
630 char *user_data = connection->OnRequest (topic_name, item, &user_size, format);
631
632 if (user_data)
633 {
634 codeco->Write8(IPC_REQUEST_REPLY);
635
636 if (user_size == -1)
637 user_size = strlen(user_data) + 1; // includes final NUL
638
639 codeco->Write32(user_size);
640 sockstrm->Write(user_data, user_size);
641 }
642 else
643 codeco->Write8(IPC_FAIL);
644
645 break;
646 }
647 case IPC_DISCONNECT:
648 {
649 sock->Notify(FALSE);
650 sock->Close();
651 connection->OnDisconnect();
652 break;
653 }
654 default:
655 codeco->Write8(IPC_FAIL);
656 break;
657 }
658 }
659
660 void wxTCPEventHandler::Server_OnRequest(wxSocketEvent &event)
661 {
662 wxSocketServer *server = (wxSocketServer *) event.GetSocket();
663 wxTCPServer *ipcserv = (wxTCPServer *) server->GetClientData();
664
665 // This socket is being deleted; skip this event
666 if (!ipcserv)
667 return;
668
669 if (event.GetSocketEvent() != wxSOCKET_CONNECTION)
670 return;
671
672 // Accept the connection, getting a new socket
673 wxSocketBase *sock = server->Accept();
674 if (!sock->Ok())
675 {
676 sock->Destroy();
677 return;
678 }
679
680 wxSocketStream *stream = new wxSocketStream(*sock);
681 wxDataInputStream *codeci = new wxDataInputStream(*stream);
682 wxDataOutputStream *codeco = new wxDataOutputStream(*stream);
683
684 int msg;
685 msg = codeci->Read8();
686
687 if (msg == IPC_CONNECT)
688 {
689 wxString topic_name;
690 topic_name = codeci->ReadString();
691
692 wxTCPConnection *new_connection =
693 (wxTCPConnection *)ipcserv->OnAcceptConnection (topic_name);
694
695 if (new_connection)
696 {
697 if (new_connection->IsKindOf(CLASSINFO(wxTCPConnection)))
698 {
699 // Acknowledge success
700 codeco->Write8(IPC_CONNECT);
701 new_connection->m_topic = topic_name;
702 new_connection->m_sock = sock;
703 new_connection->m_sockstrm = stream;
704 new_connection->m_codeci = codeci;
705 new_connection->m_codeco = codeco;
706 sock->SetEventHandler(*gs_handler, _CLIENT_ONREQUEST_ID);
707 sock->SetClientData(new_connection);
708 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
709 sock->Notify(TRUE);
710 return;
711 }
712 else
713 {
714 delete new_connection;
715 // and fall through to delete everything else
716 }
717 }
718 }
719
720 // Something went wrong, send failure message and delete everything
721 codeco->Write8(IPC_FAIL);
722
723 delete codeco;
724 delete codeci;
725 delete stream;
726 sock->Destroy();
727 }
728
729 // --------------------------------------------------------------------------
730 // wxTCPEventHandlerModule (private class)
731 // --------------------------------------------------------------------------
732
733 class WXDLLEXPORT wxTCPEventHandlerModule: public wxModule
734 {
735 DECLARE_DYNAMIC_CLASS(wxTCPEventHandlerModule)
736
737 public:
738 bool OnInit() { gs_handler = new wxTCPEventHandler(); return TRUE; }
739 void OnExit() { wxDELETE(gs_handler); }
740 };
741
742 IMPLEMENT_DYNAMIC_CLASS(wxTCPEventHandlerModule, wxModule)
743
744
745 #endif
746 // wxUSE_SOCKETS && wxUSE_IPC