Debian Codegraph @

protolib/src/common/protoPipe.cpp

raw
1 /**
2 * @file protoPipe.cpp
3 *
4 * @brief Provides a cross-platform interprocess communication mechanism for
5 * Protolib using Unix-domain sockets (UNIX) or similar locally bound sockets mechanisms (WIN32).
6 * This class extends the "ProtoSocket" class to support "LOCAL" domain interprocess communications
7 */
8 #include "protoPipe.h"
9 #include "protoDebug.h"
10
11 #ifdef WIN32
12 #include <winreg.h>
13 #include <tchar.h>
14 #else
15 #include <unistd.h> // for unlink(), close()
16 #include <sys/un.h> // for unix domain sockets
17 #include <sys/stat.h>
18 #include <stdlib.h> // for mkstemp()
19 #ifdef NO_SCM_RIGHTS
20 #undef SCM_RIGHTS
21 #endif // NO_SCM_RIGHTS
22 #define CLI_PERM S_IRWXU
23 #endif // if/else WIN32
24
25 ProtoPipe::ProtoPipe(Type theType)
26 : ProtoSocket((MESSAGE == theType) ? UDP : TCP),
27 #ifdef WIN32
28 named_event_handle(INVALID_HANDLE_VALUE)
29 #else // UNIX
30 unlink_tried(false)
31 #endif // if/else WIN32/UNIX
32 {
33 domain = LOCAL;
34 path[0] = '\0';
35 }
36
37 ProtoPipe::~ProtoPipe()
38 {
39 Close();
40 }
41
42 #ifdef WIN32
43
44 void ProtoPipe::Close()
45 {
46 if (IsOpen())
47 {
48 ProtoSocket::Close();
49 // Remove registry entry if we're a listener
50 if ('\0' != path[0])
51 {
52 #ifdef _UNICODE
53 wchar_t wideBuffer[PATH_MAX];
54 mbstowcs(wideBuffer, path, strlen(path)+1);
55 LPCTSTR namePtr = wideBuffer;
56 #else
57 LPCSTR namePtr = path;
58 #endif // if/else _UNICODE
59 HKEY hKey;
60 if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
61 _T("Software\\Protokit"),
62 0, KEY_SET_VALUE, &hKey))
63 {
64 if (ERROR_SUCCESS != RegDeleteValue(hKey, namePtr))
65 PLOG(PL_ERROR, "ProtoPipe::Close() RegDeleteValue() error: %s\n", ::GetErrorString());
66 RegCloseKey(hKey);
67 }
68 else
69 {
70 PLOG(PL_ERROR, "ProtoPipe::Close() RegOpenKeyEx() error: %s\n", ::GetErrorString());
71 }
72 }
73 if (INVALID_HANDLE_VALUE != named_event_handle)
74 {
75 CloseHandle(named_event_handle);
76 named_event_handle = INVALID_HANDLE_VALUE;
77 }
78 } // end if IsOpen()
79 } // end ProtoPipe::Close()
80
81 /**
82 * Setup event handles and overlapped structures. Set up pipes.
83 * Start overlapped notifications and initiate overlapped I/O.
84 */
85
86 bool ProtoPipe::Listen(const char* theName)
87 {
88 // This "pipe" implementation uses the WIN32 registry to find "local" sockets
89 // which are used to provide interprocess "pipe" connectivity
90 if (NULL != named_event_handle) CloseHandle(named_event_handle);
91
92 // 1) Try to open named event for "theName"
93 char pipeName[MAX_PATH];
94 strcpy(pipeName, "Global\\protoPipe-");
95 strncat(pipeName, theName, MAX_PATH - strlen(pipeName));
96 #ifdef _UNICODE
97 wchar_t wideBuffer[MAX_PATH];
98 mbstowcs(wideBuffer, pipeName, strlen(pipeName)+1);
99 LPCTSTR namePtr = wideBuffer;
100 #else
101 LPCTSTR namePtr = pipeName;
102 #endif // if/else _UNICODE
103 named_event_handle = CreateEvent(NULL, TRUE, TRUE, namePtr);
104 if (NULL == named_event_handle)
105 {
106 named_event_handle = INVALID_HANDLE_VALUE;
107 PLOG(PL_ERROR, "ProtoPipe::Listen() CreateEvent() error: %s\n", ::GetErrorString());
108 return false;
109 }
110 else if (ERROR_ALREADY_EXISTS == GetLastError())
111 {
112 PLOG(PL_ERROR, "ProtoPipe::Listen() error: pipe already exists\n");
113 Close();
114 return false;
115 }
116
117 // 2) Open/Listen
118 if (ProtoSocket::Listen())
119 {
120 // Make a registry entry so "connecting" pipes can find the port number
121 HKEY hKey;
122 DWORD dwAction;
123 long theError = 0;
124
125 if (ERROR_SUCCESS == RegCreateKeyEx(HKEY_LOCAL_MACHINE,
126 _T("Software\\Protokit"),
127 0L,
128 NULL,
129 REG_OPTION_NON_VOLATILE,
130 KEY_ALL_ACCESS,
131 NULL,
132 &hKey,
133 &dwAction))
134 {
135 #ifdef _UNICODE
136 mbstowcs(wideBuffer, theName, strlen(theName)+1);
137 namePtr = wideBuffer;
138 #else
139 namePtr = theName;
140 #endif // if/else _UNICODE;
141 DWORD thePort = (DWORD)ProtoSocket::GetPort();
142 if (ERROR_SUCCESS != RegSetValueEx(hKey, namePtr, 0L, REG_DWORD,
143 (BYTE*)&thePort, sizeof(DWORD)))
144 {
145 PLOG(PL_ERROR, "ProtoPipe::Listen() RegSetValueEx() error: %s\n", ::GetErrorString());
146 RegCloseKey(hKey);
147 Close();
148 return false;
149 }
150 RegCloseKey(hKey);
151 }
152 else
153 {
154 PLOG(PL_ERROR, "ProtoPipe::Listen() RegCreateKeyEx() error: %s (Must be run as administrator)\n", ::GetErrorString());
155 Close();
156 return false;
157 }
158 }
159 else
160 {
161 PLOG(PL_ERROR, "ProtoPipe::Listen() error listening to socket\n");
162 Close();
163 return false;
164 }
165 // Save our named event path name
166 strncpy(path, theName, PATH_MAX);
167 return true;
168 } // ProtoPipe::Listen()
169
170 bool ProtoPipe::Accept(ProtoPipe* thePipe)
171 {
172 return ProtoSocket::Accept(static_cast<ProtoSocket*>(thePipe));
173 } // end ProtoPipe::Accept()
174
175
176 bool ProtoPipe::Connect(const char* theName)
177 {
178 // 1) Open the named event given the pipe name
179 // This "pipe" implementation uses the registry to find "local" sockets
180 // which are used to provide interprocess "pipe" connectivity
181 if (INVALID_HANDLE_VALUE != named_event_handle) CloseHandle(named_event_handle);
182
183 // 1) Try to open name event of using given name
184 char pipeName[MAX_PATH];
185 strcpy(pipeName, "Global\\protoPipe-");
186 strncat(pipeName, theName, MAX_PATH - strlen(pipeName));
187 #ifdef _UNICODE
188 wchar_t wideBuffer[MAX_PATH];
189 mbstowcs(wideBuffer, pipeName, strlen(pipeName)+1);
190 LPCTSTR namePtr = wideBuffer;
191 #else
192 LPCTSTR namePtr = pipeName;
193 #endif // if/else _UNICODE
194
195 named_event_handle = OpenEvent(EVENT_ALL_ACCESS, FALSE, namePtr);
196 if (NULL != named_event_handle)
197 {
198 CloseHandle(named_event_handle);
199 named_event_handle = INVALID_HANDLE_VALUE;
200 #ifdef _UNICODE
201 mbstowcs(wideBuffer, theName, strlen(theName)+1);
202 namePtr = wideBuffer;
203 #else
204 namePtr = theName;
205 #endif // if/else _UNICODE
206
207 // Now find the port number in the registry
208 DWORD thePort = 0;
209 HKEY hKey;
210 if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
211 _T("Software\\Protokit"),
212 0, KEY_READ, &hKey))
213 {
214 DWORD dwType;
215 DWORD dwLen = sizeof(DWORD);
216 if (ERROR_SUCCESS == RegQueryValueEx(hKey, namePtr, NULL, &dwType,
217 (BYTE*)&thePort, &dwLen))
218 {
219 if (REG_DWORD != dwType)
220 {
221 PLOG(PL_ERROR, "ProtoPipe::Connect() registry entry type mismatch!\n");
222 RegCloseKey(hKey);
223 Close();
224 return false;
225 }
226 }
227 else
228 {
229 PLOG(PL_ERROR, "ProtoPipe::Connect() RegQueryValueEx() error: %s\n", ::GetErrorString());
230 RegCloseKey(hKey);
231 Close();
232 return false;
233 }
234 RegCloseKey(hKey);
235 }
236 else
237 {
238 PLOG(PL_ERROR, "ProtoPipe::Connect() RegOpenKeyEx() error: %s\n", ::GetErrorString());
239 Close();
240 return false;
241 }
242
243 if ((thePort < 1) || (thePort > 0x0ffff))
244 {
245 PLOG(PL_ERROR, "ProtoPipe::Connect() error: bad port value!?\n");
246 Close();
247 return false;
248 }
249
250 // Now connect to loopback address for given port
251 ProtoAddress pipeAddr;
252 pipeAddr.ResolveFromString("127.0.0.1");
253 pipeAddr.SetPort((UINT16)thePort);
254 if (!ProtoSocket::Connect(pipeAddr))
255 {
256 PLOG(PL_ERROR, "ProtoPipe::Connect() error connecting socket!\n");
257 Close();
258 return false;
259 }
260 }
261 else
262 {
263 PLOG(PL_ERROR, "ProtoPipe::Connect() error (pipe not found): %s\n", ::GetErrorString());
264 return false;
265 }
266 return true;
267 } // end ProtoPipe::Connect()
268
269 #else // UNIX
270 /**
271 * This method opens a Unix-domain socket to serve as the ProtoPipe
272 */
273
274 bool ProtoPipe::Open(const char* theName)
275 {
276 // (TBD) use a semaphore to avoid issue of stale
277 // Unix domain socket paths causing Open() to fail ???
278 if (IsOpen()) Close();
279 char pipeName[PATH_MAX] = {0};
280 if(*theName!='/')
281 {
282 #ifdef __ANDROID__
283 strcpy(pipeName, "/data/local/tmp/");
284 #else
285 strcpy(pipeName, "/tmp/");
286 #endif // if/else __ANDROID__
287 }
288 strncat(pipeName, theName, PATH_MAX-strlen(pipeName));
289 struct sockaddr_un sockAddr;
290 memset(&sockAddr, 0, sizeof(sockAddr));
291 sockAddr.sun_family = AF_UNIX;
292 strcpy(sockAddr.sun_path, pipeName);
293 #ifdef SCM_RIGHTS /* 4.3BSD Reno and later */
294 size_t len = sizeof(sockAddr.sun_len) + sizeof(sockAddr.sun_family) +
295 strlen(sockAddr.sun_path) + 1;
296 #else
297 size_t len = strlen(sockAddr.sun_path) + sizeof(sockAddr.sun_family);
298 #endif // if/else SCM_RIGHTS
299 int socketType = (UDP == protocol) ? SOCK_DGRAM : SOCK_STREAM;
300 if ((handle = socket(AF_UNIX, socketType, 0)) < 0)
301 {
302 PLOG(PL_ERROR, "ProtoPipe::Open() socket() error: %s\n", GetErrorString());
303 Close();
304 return false;
305 }
306 if (bind(handle, (struct sockaddr*)&sockAddr, (socklen_t)len) < 0)
307 {
308 PLOG(PL_WARN, "ProtoPipe::Open() bind(%s) error: %s\n", pipeName, GetErrorString());
309 Close();
310 return false;
311 }
312 state = IDLE;
313 port = 0;
314 if (!UpdateNotification())
315 {
316 PLOG(PL_ERROR, "ProtoPipe::Open() error updating notification\n");
317 Close();
318 return false;
319 }
320 strncpy(path, theName, PATH_MAX);
321 return true;
322 } // end ProtoPipe::Open(const char* theName)
323
324
325 void ProtoPipe::Close()
326 {
327 if ('\0' != path[0])
328 {
329 Unlink(path);
330 path[0] = '\0';
331 }
332 ProtoSocket::Close();
333 } // end ProtoPipe::Close();
334
335 void ProtoPipe::Unlink(const char* theName)
336 {
337 char pipeName[PATH_MAX] = {0};
338 if(*theName!='/')
339 {
340 #ifdef __ANDROID__
341 strcpy(pipeName, "/data/local/tmp/");
342 #else
343 strcpy(pipeName, "/tmp/");
344 #endif // if/else __ANDROID__
345 }
346 strncat(pipeName, theName, PATH_MAX - strlen(pipeName));
347 unlink(pipeName);
348 } // end ProtoPipe::Unlink()
349
350 bool ProtoPipe::Listen(const char* theName)
351 {
352 if (IsOpen()) Close();
353 if (Open(theName))
354 {
355 if (TCP == protocol)
356 {
357 state = LISTENING;
358 if (!UpdateNotification())
359 {
360 PLOG(PL_ERROR, "ProtoSocket::Listen() error updating notification\n");
361 Close();
362 return false;
363 }
364 if (listen(handle, 5) < 0)
365 {
366 PLOG(PL_ERROR, "ProtoSocket:Listen() listen() error: %s\n", GetErrorString());
367 Close();
368 return false;
369 }
370 }
371 return true;
372 }
373 else
374 {
375 if (Connect(theName))
376 {
377 Close();
378 PLOG(PL_WARN, "ProtoPipe::Listen() error: name already in use\n");
379 return false;
380 }
381 else
382 {
383 #ifndef WIN32
384 if (unlink_tried)
385 {
386 unlink_tried = false;
387 }
388 else
389 {
390 Unlink(theName);
391 unlink_tried = true;
392 if (Listen(theName))
393 {
394 unlink_tried = false;
395 return true;
396 }
397 unlink_tried = false;
398 }
399 #endif
400 PLOG(PL_ERROR, "ProtoPipe::Listen() error opening pipe\n");
401 }
402 return false;
403 }
404 } // end ProtoPipe::Listen
405
406 bool ProtoPipe::Accept(ProtoPipe* thePipe)
407 {
408 return ProtoSocket::Accept(static_cast<ProtoSocket*>(thePipe));
409 } // end ProtoPipe::Accept()
410
411 bool ProtoPipe::Connect(const char* theName)
412 {
413 // (TBD) Don't "bind()" connecting sockets???
414 // Open a socket as needed
415 if (!IsOpen())
416 {
417 char pipeName[PATH_MAX];
418 #ifdef __ANDROID__
419 strcpy(pipeName, "/data/local/tmp/protoSocketXXXXXX");
420 #else
421 strcpy(pipeName, "/tmp/protoSocketXXXXXX");
422 #endif // if/else __ANDROID__
423 int fd = mkstemp(pipeName);
424 if (fd < 0)
425 {
426 PLOG(PL_ERROR, "ProtoPipe::Connect() mkstemp() error: %s\n", GetErrorString());
427 return false;
428 }
429 else
430 {
431 close(fd);
432 unlink(pipeName);
433 }
434 if (!Open(pipeName+5))
435 {
436 PLOG(PL_ERROR, "ProtoPipe::Connect() error opening local domain socket\n");
437 return false;
438 }
439
440 // Try to make socket flush before closing
441 if (TCP == protocol)
442 {
443 struct linger so_linger;
444 so_linger.l_onoff = 1;
445 so_linger.l_linger = 5000;
446 if (setsockopt(handle, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger)) < 0)
447 PLOG(PL_ERROR, "ProtoPipe::Connect() setsockopt(SO_LINGER) error: %s\n", GetErrorString());
448 }
449 // I can't remember why we do this step ...
450 if (chmod(pipeName, CLI_PERM) < 0)
451 {
452 PLOG(PL_ERROR, "ProtoPipe::Connect(): chmod() error: %s\n", GetErrorString());
453 Close();
454 return false;
455 }
456 }
457
458 // Now try to connect to server
459 struct sockaddr_un serverAddr;
460 memset(&serverAddr, 0, sizeof(serverAddr));
461 serverAddr.sun_family = AF_UNIX;
462 if(*theName!='/')
463 {
464 #ifdef __ANDROID__
465 strcpy(serverAddr.sun_path, "/data/local/tmp/");
466 #else
467 strcpy(serverAddr.sun_path, "/tmp/");
468 #endif // if/else __ANDROID__
469 }
470 size_t pathMax = sizeof(serverAddr.sun_path);
471 strncat(serverAddr.sun_path, theName, pathMax - strlen(serverAddr.sun_path));
472 #ifdef SCM_RIGHTS // 4.3BSD Reno and later
473 size_t addrLen = sizeof(serverAddr.sun_len) + sizeof(serverAddr.sun_family) +
474 strlen(serverAddr.sun_path) + 1;
475 #else
476 int addrLen = strlen(serverAddr.sun_path) + sizeof(serverAddr.sun_family);
477 #endif // SCM_RIGHTS
478 // Make sure socket is "blocking" before connect attempt for "local socket
479 ProtoPipe::Notifier* savedNotifier = notifier;
480 if (NULL != savedNotifier) SetNotifier((ProtoPipe::Notifier*)NULL);
481 if (connect(handle, (struct sockaddr*)&serverAddr, (socklen_t)addrLen) < 0)
482 {
483 PLOG(PL_DEBUG, "ProtoPipe::Connect(): connect() error: %s\n", GetErrorString());
484 Close();
485 // Restore socket notification if applicable
486 if (NULL != savedNotifier) SetNotifier(savedNotifier);
487 return false;
488 }
489 // Restore socket notification if applicable
490 if (NULL != savedNotifier) SetNotifier(savedNotifier);
491 state = CONNECTED;
492 if (!UpdateNotification())
493 {
494 PLOG(PL_ERROR, "ProtoPipe::Connect() error updating notification\n");
495 Close();
496 return false;
497 }
498 return true;
499 } // end ProtoPipe::Connect()
500
501
502 #endif // if/else WIN32/UNIX