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