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