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