1 /**************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21
22
23
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_desktop.hxx"
26
27 #include "app.hxx"
28 #include "officeipcthread.hxx"
29 #include "cmdlineargs.hxx"
30 #include "dispatchwatcher.hxx"
31 #include <memory>
32 #include <stdio.h>
33 #include <vos/process.hxx>
34 #include <unotools/bootstrap.hxx>
35 #include <vcl/svapp.hxx>
36 #include <vcl/help.hxx>
37 #include <unotools/configmgr.hxx>
38 #include <osl/thread.hxx>
39 #include <rtl/digest.h>
40 #include <rtl/ustrbuf.hxx>
41 #include <rtl/instance.hxx>
42 #include <osl/conditn.hxx>
43 #include <unotools/moduleoptions.hxx>
44 #include <rtl/bootstrap.hxx>
45 #include <rtl/strbuf.hxx>
46 #include <comphelper/processfactory.hxx>
47 #include "osl/file.hxx"
48 #include "rtl/process.h"
49 #include "tools/getprocessworkingdir.hxx"
50
51 using namespace vos;
52 using namespace rtl;
53 using namespace desktop;
54 using namespace ::com::sun::star::uno;
55 using namespace ::com::sun::star::lang;
56 using namespace ::com::sun::star::frame;
57
58 const char *OfficeIPCThread::sc_aTerminationSequence = "InternalIPC::TerminateThread";
59 const int OfficeIPCThread::sc_nTSeqLength = 28;
60 const char *OfficeIPCThread::sc_aShowSequence = "-tofront";
61 const int OfficeIPCThread::sc_nShSeqLength = 5;
62 const char *OfficeIPCThread::sc_aConfirmationSequence = "InternalIPC::ProcessingDone";
63 const int OfficeIPCThread::sc_nCSeqLength = 27;
64
65 namespace { static char const ARGUMENT_PREFIX[] = "InternalIPC::Arguments"; }
66
67 // Type of pipe we use
68 enum PipeMode
69 {
70 PIPEMODE_DONTKNOW,
71 PIPEMODE_CREATED,
72 PIPEMODE_CONNECTED
73 };
74
75 namespace desktop
76 {
77
78 namespace {
79
80 class Parser: public CommandLineArgs::Supplier {
81 public:
Parser(rtl::OString const & input)82 explicit Parser(rtl::OString const & input): m_input(input) {
83 if (!m_input.match(ARGUMENT_PREFIX) ||
84 m_input.getLength() == RTL_CONSTASCII_LENGTH(ARGUMENT_PREFIX))
85 {
86 throw CommandLineArgs::Supplier::Exception();
87 }
88 m_index = RTL_CONSTASCII_LENGTH(ARGUMENT_PREFIX);
89 switch (m_input[m_index++]) {
90 case '0':
91 break;
92 case '1':
93 {
94 rtl::OUString url;
95 if (!next(&url, false)) {
96 throw CommandLineArgs::Supplier::Exception();
97 }
98 m_cwdUrl.reset(url);
99 break;
100 }
101 case '2':
102 {
103 rtl::OUString path;
104 if (!next(&path, false)) {
105 throw CommandLineArgs::Supplier::Exception();
106 }
107 rtl::OUString url;
108 if (osl::FileBase::getFileURLFromSystemPath(path, url) ==
109 osl::FileBase::E_None)
110 {
111 m_cwdUrl.reset(url);
112 }
113 break;
114 }
115 default:
116 throw CommandLineArgs::Supplier::Exception();
117 }
118 }
119
~Parser()120 virtual ~Parser() {}
121
getCwdUrl()122 virtual boost::optional< rtl::OUString > getCwdUrl() { return m_cwdUrl; }
123
next(rtl::OUString * argument)124 virtual bool next(rtl::OUString * argument) { return next(argument, true); }
125
126 private:
next(rtl::OUString * argument,bool prefix)127 virtual bool next(rtl::OUString * argument, bool prefix) {
128 OSL_ASSERT(argument != NULL);
129 if (m_index < m_input.getLength()) {
130 if (prefix) {
131 if (m_input[m_index] != ',') {
132 throw CommandLineArgs::Supplier::Exception();
133 }
134 ++m_index;
135 }
136 rtl::OStringBuffer b;
137 while (m_index < m_input.getLength()) {
138 char c = m_input[m_index];
139 if (c == ',') {
140 break;
141 }
142 ++m_index;
143 if (c == '\\') {
144 if (m_index < m_input.getLength()) {
145 c = m_input[m_index++];
146 switch (c) {
147 case '0':
148 c = '\0';
149 break;
150 case ',':
151 case '\\':
152 break;
153 default:
154 throw CommandLineArgs::Supplier::Exception();
155 }
156 } else {
157 throw CommandLineArgs::Supplier::Exception();
158 }
159 }
160 b.append(c);
161 }
162 rtl::OString b2(b.makeStringAndClear());
163 if (!rtl_convertStringToUString(
164 &argument->pData, b2.getStr(), b2.getLength(),
165 RTL_TEXTENCODING_UTF8,
166 (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR |
167 RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR |
168 RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR)))
169 {
170 throw CommandLineArgs::Supplier::Exception();
171 }
172 return true;
173 } else {
174 return false;
175 }
176 }
177
178 boost::optional< rtl::OUString > m_cwdUrl;
179 rtl::OString m_input;
180 sal_Int32 m_index;
181 };
182
addArgument(ByteString * arguments,char prefix,rtl::OUString const & argument)183 bool addArgument(
184 ByteString * arguments, char prefix, rtl::OUString const & argument)
185 {
186 rtl::OString utf8;
187 if (!argument.convertToString(
188 &utf8, RTL_TEXTENCODING_UTF8,
189 (RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
190 RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR)))
191 {
192 return false;
193 }
194 *arguments += prefix;
195 for (sal_Int32 i = 0; i < utf8.getLength(); ++i) {
196 char c = utf8[i];
197 switch (c) {
198 case '\0':
199 *arguments += "\\0";
200 break;
201 case ',':
202 *arguments += "\\,";
203 break;
204 case '\\':
205 *arguments += "\\\\";
206 break;
207 default:
208 *arguments += c;
209 break;
210 }
211 }
212 return true;
213 }
214
215 }
216
217 OfficeIPCThread* OfficeIPCThread::pGlobalOfficeIPCThread = 0;
218 namespace { struct Security : public rtl::Static<OSecurity, Security> {}; }
219 ::osl::Mutex* OfficeIPCThread::pOfficeIPCThreadMutex = 0;
220
221
CreateMD5FromString(const OUString & aMsg)222 String CreateMD5FromString( const OUString& aMsg )
223 {
224 // PRE: aStr "file"
225 // BACK: Str "ababab....0f" Hexcode String
226
227 rtlDigest handle = rtl_digest_create( rtl_Digest_AlgorithmMD5 );
228 if ( handle != NULL )
229 {
230 const sal_uInt8* pData = (const sal_uInt8*)aMsg.getStr();
231 sal_uInt32 nSize = ( aMsg.getLength() * sizeof( sal_Unicode ));
232 sal_uInt32 nMD5KeyLen = rtl_digest_queryLength( handle );
233 sal_uInt8* pMD5KeyBuffer = new sal_uInt8[ nMD5KeyLen ];
234
235 rtl_digest_init( handle, pData, nSize );
236 rtl_digest_update( handle, pData, nSize );
237 rtl_digest_get( handle, pMD5KeyBuffer, nMD5KeyLen );
238 rtl_digest_destroy( handle );
239
240 // Create hex-value string from the MD5 value to keep the string size minimal
241 OUStringBuffer aBuffer( nMD5KeyLen * 2 + 1 );
242 for ( sal_uInt32 i = 0; i < nMD5KeyLen; i++ )
243 aBuffer.append( (sal_Int32)pMD5KeyBuffer[i], 16 );
244
245 delete [] pMD5KeyBuffer;
246 return aBuffer.makeStringAndClear();
247 }
248
249 return String();
250 }
251
252 class ProcessEventsClass_Impl
253 {
254 public:
255 DECL_STATIC_LINK( ProcessEventsClass_Impl, CallEvent, void* pEvent );
256 DECL_STATIC_LINK( ProcessEventsClass_Impl, ProcessDocumentsEvent, void* pEvent );
257 };
258
IMPL_STATIC_LINK_NOINSTANCE(ProcessEventsClass_Impl,CallEvent,void *,pEvent)259 IMPL_STATIC_LINK_NOINSTANCE( ProcessEventsClass_Impl, CallEvent, void*, pEvent )
260 {
261 // Application events are processed by the Desktop::HandleAppEvent implementation.
262 Desktop::HandleAppEvent( *((ApplicationEvent*)pEvent) );
263 delete (ApplicationEvent*)pEvent;
264 return 0;
265 }
266
IMPL_STATIC_LINK_NOINSTANCE(ProcessEventsClass_Impl,ProcessDocumentsEvent,void *,pEvent)267 IMPL_STATIC_LINK_NOINSTANCE( ProcessEventsClass_Impl, ProcessDocumentsEvent, void*, pEvent )
268 {
269 // Documents requests are processed by the OfficeIPCThread implementation
270 ProcessDocumentsRequest* pDocsRequest = (ProcessDocumentsRequest*)pEvent;
271
272 if ( pDocsRequest )
273 {
274 OfficeIPCThread::ExecuteCmdLineRequests( *pDocsRequest );
275 delete pDocsRequest;
276 }
277 return 0;
278 }
279
ImplPostForeignAppEvent(ApplicationEvent * pEvent)280 void ImplPostForeignAppEvent( ApplicationEvent* pEvent )
281 {
282 Application::PostUserEvent( STATIC_LINK( NULL, ProcessEventsClass_Impl, CallEvent ), pEvent );
283 }
284
ImplPostProcessDocumentsEvent(ProcessDocumentsRequest * pEvent)285 void ImplPostProcessDocumentsEvent( ProcessDocumentsRequest* pEvent )
286 {
287 Application::PostUserEvent( STATIC_LINK( NULL, ProcessEventsClass_Impl, ProcessDocumentsEvent ), pEvent );
288 }
289
signal(TSignalInfo * pInfo)290 OSignalHandler::TSignalAction SAL_CALL SalMainPipeExchangeSignalHandler::signal(TSignalInfo *pInfo)
291 {
292 if( pInfo->Signal == osl_Signal_Terminate )
293 OfficeIPCThread::DisableOfficeIPCThread();
294 return (TAction_CallNextHandler);
295 }
296
297 // ----------------------------------------------------------------------------
298
299 // The OfficeIPCThreadController implementation is a bookkeeper for all pending requests
300 // that were created by the OfficeIPCThread. The requests are waiting to be processed by
301 // our framework loadComponentFromURL function (e.g. open/print request).
302 // During shutdown the framework is asking OfficeIPCThreadController about pending requests.
303 // If there are pending requests framework has to stop the shutdown process. It is waiting
304 // for these requests because framework is not able to handle shutdown and open a document
305 // concurrently.
306
307
308 // XServiceInfo
getImplementationName()309 OUString SAL_CALL OfficeIPCThreadController::getImplementationName()
310 {
311 return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.OfficeIPCThreadController" ));
312 }
313
supportsService(const OUString &)314 sal_Bool SAL_CALL OfficeIPCThreadController::supportsService( const OUString& )
315 {
316 return sal_False;
317 }
318
getSupportedServiceNames()319 Sequence< OUString > SAL_CALL OfficeIPCThreadController::getSupportedServiceNames()
320 {
321 Sequence< OUString > aSeq( 0 );
322 return aSeq;
323 }
324
325 // XEventListener
disposing(const EventObject &)326 void SAL_CALL OfficeIPCThreadController::disposing( const EventObject& )
327 {
328 }
329
330 // XTerminateListener
queryTermination(const EventObject &)331 void SAL_CALL OfficeIPCThreadController::queryTermination( const EventObject& )
332 {
333 // Desktop ask about pending request through our office ipc pipe. We have to
334 // be sure that no pending request is waiting because framework is not able to
335 // handle shutdown and open a document concurrently.
336
337 if ( OfficeIPCThread::AreRequestsPending() )
338 throw TerminationVetoException();
339 else
340 OfficeIPCThread::SetDowning();
341 }
342
notifyTermination(const EventObject &)343 void SAL_CALL OfficeIPCThreadController::notifyTermination( const EventObject& )
344 {
345 }
346
347 // ----------------------------------------------------------------------------
348
GetMutex()349 ::osl::Mutex& OfficeIPCThread::GetMutex()
350 {
351 // Get or create our mutex for thread-safety
352 if ( !pOfficeIPCThreadMutex )
353 {
354 ::osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() );
355 if ( !pOfficeIPCThreadMutex )
356 pOfficeIPCThreadMutex = new osl::Mutex;
357 }
358
359 return *pOfficeIPCThreadMutex;
360 }
361
SetDowning()362 void OfficeIPCThread::SetDowning()
363 {
364 // We have the order to block all incoming requests. Framework
365 // wants to shutdown and we have to make sure that no loading/printing
366 // requests are executed anymore.
367 ::osl::MutexGuard aGuard( GetMutex() );
368
369 if ( pGlobalOfficeIPCThread )
370 pGlobalOfficeIPCThread->mbDowning = true;
371 }
372
373 static bool s_bInEnableRequests = false;
374
EnableRequests(bool i_bEnable)375 void OfficeIPCThread::EnableRequests( bool i_bEnable )
376 {
377 // switch between just queueing the requests and executing them
378 ::osl::MutexGuard aGuard( GetMutex() );
379
380 if ( pGlobalOfficeIPCThread )
381 {
382 s_bInEnableRequests = true;
383 pGlobalOfficeIPCThread->mbRequestsEnabled = i_bEnable;
384 if( i_bEnable )
385 {
386 // hit the compiler over the head
387 ProcessDocumentsRequest aEmptyReq = ProcessDocumentsRequest( boost::optional< rtl::OUString >() );
388 // trigger already queued requests
389 OfficeIPCThread::ExecuteCmdLineRequests( aEmptyReq );
390 }
391 s_bInEnableRequests = false;
392 }
393 }
394
AreRequestsPending()395 sal_Bool OfficeIPCThread::AreRequestsPending()
396 {
397 // Give info about pending requests
398 ::osl::MutexGuard aGuard( GetMutex() );
399 if ( pGlobalOfficeIPCThread )
400 return ( pGlobalOfficeIPCThread->mnPendingRequests > 0 );
401 else
402 return sal_False;
403 }
404
RequestsCompleted(int nCount)405 void OfficeIPCThread::RequestsCompleted( int nCount )
406 {
407 // Remove nCount pending requests from our internal counter
408 ::osl::MutexGuard aGuard( GetMutex() );
409 if ( pGlobalOfficeIPCThread )
410 {
411 if ( pGlobalOfficeIPCThread->mnPendingRequests > 0 )
412 pGlobalOfficeIPCThread->mnPendingRequests -= nCount;
413 }
414 }
415
EnableOfficeIPCThread()416 OfficeIPCThread::Status OfficeIPCThread::EnableOfficeIPCThread()
417 {
418 ::osl::MutexGuard aGuard( GetMutex() );
419
420 if( pGlobalOfficeIPCThread )
421 return IPC_STATUS_OK;
422
423 ::rtl::OUString aUserInstallPath;
424 ::rtl::OUString aDummy;
425
426 ::vos::OStartupInfo aInfo;
427 OfficeIPCThread* pThread = new OfficeIPCThread;
428
429 pThread->maPipeIdent = OUString( RTL_CONSTASCII_USTRINGPARAM( "SingleOfficeIPC_" ) );
430
431 // The name of the named pipe is created with the hashcode of the user installation directory (without /user). We have to retrieve
432 // this information from a unotools implementation.
433 ::utl::Bootstrap::PathStatus aLocateResult = ::utl::Bootstrap::locateUserInstallation( aUserInstallPath );
434 if ( aLocateResult == ::utl::Bootstrap::PATH_EXISTS || aLocateResult == ::utl::Bootstrap::PATH_VALID)
435 aDummy = aUserInstallPath;
436 else
437 {
438 delete pThread;
439 return IPC_STATUS_BOOTSTRAP_ERROR;
440 }
441
442 // Try to determine if we are the first office or not! This should prevent multiple
443 // access to the user directory !
444 // First we try to create our pipe if this fails we try to connect. We have to do this
445 // in a loop because the other office can crash or shutdown between createPipe
446 // and connectPipe!!
447
448 OUString aIniName;
449
450 aInfo.getExecutableFile( aIniName );
451 sal_uInt32 lastIndex = aIniName.lastIndexOf('/');
452 if ( lastIndex > 0 )
453 {
454 aIniName = aIniName.copy( 0, lastIndex+1 );
455 aIniName += OUString( RTL_CONSTASCII_USTRINGPARAM( "perftune" ));
456 #if defined(WNT) || defined(OS2)
457 aIniName += OUString( RTL_CONSTASCII_USTRINGPARAM( ".ini" ));
458 #else
459 aIniName += OUString( RTL_CONSTASCII_USTRINGPARAM( "rc" ));
460 #endif
461 }
462
463 ::rtl::Bootstrap aPerfTuneIniFile( aIniName );
464
465 OUString aDefault( RTL_CONSTASCII_USTRINGPARAM( "0" ));
466 OUString aPreloadData;
467
468 aPerfTuneIniFile.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "FastPipeCommunication" )), aPreloadData, aDefault );
469
470
471 OUString aUserInstallPathHashCode;
472
473 if ( aPreloadData.equalsAscii( "1" ))
474 {
475 sal_Char szBuffer[32];
476 sprintf( szBuffer, "%d", SUPD );
477 aUserInstallPathHashCode = OUString( szBuffer, strlen(szBuffer), osl_getThreadTextEncoding() );
478 }
479 else
480 aUserInstallPathHashCode = CreateMD5FromString( aDummy );
481
482
483 // Check result to create a hash code from the user install path
484 if ( aUserInstallPathHashCode.getLength() == 0 )
485 return IPC_STATUS_BOOTSTRAP_ERROR; // Something completely broken, we cannot create a valid hash code!
486
487 pThread->maPipeIdent = pThread->maPipeIdent + aUserInstallPathHashCode;
488
489 PipeMode nPipeMode = PIPEMODE_DONTKNOW;
490 do
491 {
492 OSecurity &rSecurity = Security::get();
493 // #119950# Try to connect pipe first. If connected, means another instance already launched.
494 if( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Open, rSecurity ))
495 {
496 // #119950# Test if launched in a new terminal session for same user. On Windows platform, normally a user is restricted
497 // to have only one terminal session. But if multiple terminal session for one user is allowed, crash will happen if launched
498 // OpenOffice from more than one terminal session. So need to detect and prevent this happen.
499
500 // Will try to create a same name pipe. If creation is successfully, means current instance is launched in a new session.
501 vos::OPipe maSessionPipe;
502 if ( maSessionPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Create, rSecurity )) {
503 // Can create a pipe with same name. This can only happen in multiple terminal session environment on Windows platform.
504 // Will display a warning dialog and exit.
505 return IPC_STATUS_MULTI_TS_ERROR;
506 } else {
507 // Pipe connected to first office
508 nPipeMode = PIPEMODE_CONNECTED;
509 }
510
511 }
512 else if ( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Create, rSecurity )) // Connection not successful, now we try to create
513 {
514 // Pipe created
515 nPipeMode = PIPEMODE_CREATED;
516 }
517 else
518 {
519 OPipe::TPipeError eReason = pThread->maPipe.getError();
520 if ((eReason == OPipe::E_ConnectionRefused) || (eReason == OPipe::E_invalidError))
521 return IPC_STATUS_BOOTSTRAP_ERROR;
522
523 // Wait for second office to be ready
524 TimeValue aTimeValue;
525 aTimeValue.Seconds = 0;
526 aTimeValue.Nanosec = 10000000; // 10ms
527 osl::Thread::wait( aTimeValue );
528 }
529
530 } while ( nPipeMode == PIPEMODE_DONTKNOW );
531
532 if ( nPipeMode == PIPEMODE_CREATED )
533 {
534 // Seems we are the one and only, so start listening thread
535 pGlobalOfficeIPCThread = pThread;
536 pThread->create(); // starts thread
537 }
538 else
539 {
540 // Seems another office is running. Pipe arguments to it and self terminate
541 pThread->maStreamPipe = pThread->maPipe;
542
543 sal_Bool bWaitBeforeClose = sal_False;
544 ByteString aArguments(RTL_CONSTASCII_STRINGPARAM(ARGUMENT_PREFIX));
545 rtl::OUString cwdUrl;
546 if (!(tools::getProcessWorkingDir(&cwdUrl) &&
547 addArgument(&aArguments, '1', cwdUrl)))
548 {
549 aArguments += '0';
550 }
551 sal_uInt32 nCount = rtl_getAppCommandArgCount();
552 for( sal_uInt32 i=0; i < nCount; i++ )
553 {
554 rtl_getAppCommandArg( i, &aDummy.pData );
555 if( aDummy.indexOf('-',0) != 0 )
556 {
557 bWaitBeforeClose = sal_True;
558 }
559 if (!addArgument(&aArguments, ',', aDummy)) {
560 return IPC_STATUS_BOOTSTRAP_ERROR;
561 }
562 }
563 // finally, write the string onto the pipe
564 pThread->maStreamPipe.write( aArguments.GetBuffer(), aArguments.Len() );
565 pThread->maStreamPipe.write( "\0", 1 );
566
567 // wait for confirmation #95361# #95425#
568 ByteString aToken(sc_aConfirmationSequence);
569 char *aReceiveBuffer = new char[aToken.Len()+1];
570 int n = pThread->maStreamPipe.read( aReceiveBuffer, aToken.Len() );
571 aReceiveBuffer[n]='\0';
572
573 delete pThread;
574 if (aToken.CompareTo(aReceiveBuffer)!= COMPARE_EQUAL) {
575 // something went wrong
576 delete[] aReceiveBuffer;
577 return IPC_STATUS_BOOTSTRAP_ERROR;
578 } else {
579 delete[] aReceiveBuffer;
580 return IPC_STATUS_2ND_OFFICE;
581 }
582 }
583
584 return IPC_STATUS_OK;
585 }
586
DisableOfficeIPCThread()587 void OfficeIPCThread::DisableOfficeIPCThread()
588 {
589 osl::ClearableMutexGuard aMutex( GetMutex() );
590
591 if( pGlobalOfficeIPCThread )
592 {
593 OfficeIPCThread *pOfficeIPCThread = pGlobalOfficeIPCThread;
594 pGlobalOfficeIPCThread = 0;
595
596 // send thread a termination message
597 // this is done so the subsequent join will not hang
598 // because the thread hangs in accept of pipe
599 OPipe Pipe( pOfficeIPCThread->maPipeIdent, OPipe::TOption_Open, Security::get() );
600 //Pipe.send( TERMINATION_SEQUENCE, TERMINATION_LENGTH );
601 if (Pipe.isValid())
602 {
603 Pipe.send( sc_aTerminationSequence, sc_nTSeqLength+1 ); // also send 0-byte
604
605 // close the pipe so that the streampipe on the other
606 // side produces EOF
607 Pipe.close();
608 }
609
610 // release mutex to avoid deadlocks
611 aMutex.clear();
612
613 OfficeIPCThread::SetReady(pOfficeIPCThread);
614
615 // exit gracefully and join
616 pOfficeIPCThread->join();
617 delete pOfficeIPCThread;
618
619
620 }
621 }
622
OfficeIPCThread()623 OfficeIPCThread::OfficeIPCThread() :
624 mbDowning( false ),
625 mbRequestsEnabled( false ),
626 mnPendingRequests( 0 ),
627 mpDispatchWatcher( 0 )
628 {
629 }
630
~OfficeIPCThread()631 OfficeIPCThread::~OfficeIPCThread()
632 {
633 ::osl::ClearableMutexGuard aGuard( GetMutex() );
634
635 if ( mpDispatchWatcher )
636 mpDispatchWatcher->release();
637 maPipe.close();
638 maStreamPipe.close();
639 pGlobalOfficeIPCThread = 0;
640 }
641
AddURLToStringList(const rtl::OUString & aURL,rtl::OUString & aStringList)642 static void AddURLToStringList( const rtl::OUString& aURL, rtl::OUString& aStringList )
643 {
644 if ( aStringList.getLength() )
645 aStringList += ::rtl::OUString::valueOf( (sal_Unicode)APPEVENT_PARAM_DELIMITER );
646 aStringList += aURL;
647 }
648
SetReady(OfficeIPCThread * pThread)649 void OfficeIPCThread::SetReady(OfficeIPCThread* pThread)
650 {
651 if (pThread == NULL) pThread = pGlobalOfficeIPCThread;
652 if (pThread != NULL)
653 {
654 pThread->cReady.set();
655 }
656 }
657
run()658 void SAL_CALL OfficeIPCThread::run()
659 {
660 do
661 {
662 OPipe::TPipeError
663 nError = maPipe.accept( maStreamPipe );
664
665
666 if( nError == OStreamPipe::E_None )
667 {
668
669 // #111143# and others:
670 // if we receive a request while the office is displaying some dialog or error during
671 // bootstrap, that dialogs event loop might get events that are dispatched by this thread
672 // we have to wait for cReady to be set by the real main loop.
673 // only requests that don't dispatch events may be processed before cReady is set.
674 cReady.wait();
675
676 // we might have decided to shutdown while we were sleeping
677 if (!pGlobalOfficeIPCThread) return;
678
679 // only lock the mutex when processing starts, otherwise we deadlock when the office goes
680 // down during wait
681 osl::ClearableMutexGuard aGuard( GetMutex() );
682
683 ByteString aArguments;
684 // test byte by byte
685 const int nBufSz = 2048;
686 char pBuf[nBufSz];
687 int nBytes = 0;
688 int nResult = 0;
689 // read into pBuf until '\0' is read or read-error
690 while ((nResult=maStreamPipe.recv( pBuf+nBytes, nBufSz-nBytes))>0) {
691 nBytes += nResult;
692 if (pBuf[nBytes-1]=='\0') {
693 aArguments += pBuf;
694 break;
695 }
696 }
697 // don't close pipe ...
698
699 // #90717# Is this a lookup message from another application? if so, ignore
700 if ( aArguments.Len() == 0 )
701 continue;
702
703 // is this a termination message ? if so, terminate
704 if(( aArguments.CompareTo( sc_aTerminationSequence, sc_nTSeqLength ) == COMPARE_EQUAL ) ||
705 mbDowning ) return;
706 String aEmpty;
707 std::auto_ptr< CommandLineArgs > aCmdLineArgs;
708 try
709 {
710 Parser p( aArguments );
711 aCmdLineArgs.reset( new CommandLineArgs( p ) );
712 }
713 catch ( CommandLineArgs::Supplier::Exception & )
714 {
715 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
716 fprintf( stderr, "Error in received command line arguments\n" );
717 #endif
718 continue;
719 }
720 CommandLineArgs *pCurrentCmdLineArgs = Desktop::GetCommandLineArgs();
721
722 if ( aCmdLineArgs->IsQuickstart() )
723 {
724 // we have to use application event, because we have to start quickstart service in main thread!!
725 ApplicationEvent* pAppEvent =
726 new ApplicationEvent( aEmpty, aEmpty,
727 "QUICKSTART", aEmpty );
728 ImplPostForeignAppEvent( pAppEvent );
729 }
730
731 // handle request for acceptor
732 sal_Bool bAcceptorRequest = sal_False;
733 OUString aAcceptString;
734 if ( aCmdLineArgs->GetAcceptString(aAcceptString) && Desktop::CheckOEM()) {
735 ApplicationEvent* pAppEvent =
736 new ApplicationEvent( aEmpty, aEmpty,
737 "ACCEPT", aAcceptString );
738 ImplPostForeignAppEvent( pAppEvent );
739 bAcceptorRequest = sal_True;
740 }
741 // handle acceptor removal
742 OUString aUnAcceptString;
743 if ( aCmdLineArgs->GetUnAcceptString(aUnAcceptString) ) {
744 ApplicationEvent* pAppEvent =
745 new ApplicationEvent( aEmpty, aEmpty,
746 "UNACCEPT", aUnAcceptString );
747 ImplPostForeignAppEvent( pAppEvent );
748 bAcceptorRequest = sal_True;
749 }
750
751 #ifndef UNX
752 // only in non-unix version, we need to handle a -help request
753 // in a running instance in order to display the command line help
754 if ( aCmdLineArgs->IsHelp() ) {
755 ApplicationEvent* pAppEvent =
756 new ApplicationEvent( aEmpty, aEmpty, "HELP", aEmpty );
757 ImplPostForeignAppEvent( pAppEvent );
758 }
759 #endif
760
761 sal_Bool bDocRequestSent = sal_False;
762 ProcessDocumentsRequest* pRequest = new ProcessDocumentsRequest(
763 aCmdLineArgs->getCwdUrl());
764 cProcessed.reset();
765 pRequest->pcProcessed = &cProcessed;
766
767 // Print requests are not dependent on the -invisible cmdline argument as they are
768 // loaded with the "hidden" flag! So they are always checked.
769 bDocRequestSent |= aCmdLineArgs->GetPrintList( pRequest->aPrintList );
770 bDocRequestSent |= ( aCmdLineArgs->GetPrintToList( pRequest->aPrintToList ) &&
771 aCmdLineArgs->GetPrinterName( pRequest->aPrinterName ) );
772
773 if ( !pCurrentCmdLineArgs->IsInvisible() )
774 {
775 // Read cmdline args that can open/create documents. As they would open a window
776 // they are only allowed if the "-invisible" is currently not used!
777 bDocRequestSent |= aCmdLineArgs->GetOpenList( pRequest->aOpenList );
778 bDocRequestSent |= aCmdLineArgs->GetViewList( pRequest->aViewList );
779 bDocRequestSent |= aCmdLineArgs->GetStartList( pRequest->aStartList );
780 bDocRequestSent |= aCmdLineArgs->GetForceOpenList( pRequest->aForceOpenList );
781 bDocRequestSent |= aCmdLineArgs->GetForceNewList( pRequest->aForceNewList );
782
783 // Special command line args to create an empty document for a given module
784
785 // #i18338# (lo)
786 // we only do this if no document was specified on the command line,
787 // since this would be inconsistent with the behaviour of
788 // the first process, see OpenClients() (call to OpenDefault()) in app.cxx
789 if ( aCmdLineArgs->HasModuleParam() && Desktop::CheckOEM() && (!bDocRequestSent))
790 {
791 SvtModuleOptions aOpt;
792 SvtModuleOptions::EFactory eFactory = SvtModuleOptions::E_WRITER;
793 if ( aCmdLineArgs->IsWriter() )
794 eFactory = SvtModuleOptions::E_WRITER;
795 else if ( aCmdLineArgs->IsCalc() )
796 eFactory = SvtModuleOptions::E_CALC;
797 else if ( aCmdLineArgs->IsDraw() )
798 eFactory = SvtModuleOptions::E_DRAW;
799 else if ( aCmdLineArgs->IsImpress() )
800 eFactory = SvtModuleOptions::E_IMPRESS;
801 else if ( aCmdLineArgs->IsBase() )
802 eFactory = SvtModuleOptions::E_DATABASE;
803 else if ( aCmdLineArgs->IsMath() )
804 eFactory = SvtModuleOptions::E_MATH;
805 else if ( aCmdLineArgs->IsGlobal() )
806 eFactory = SvtModuleOptions::E_WRITERGLOBAL;
807 else if ( aCmdLineArgs->IsWeb() )
808 eFactory = SvtModuleOptions::E_WRITERWEB;
809
810 if ( pRequest->aOpenList.getLength() )
811 pRequest->aModule = aOpt.GetFactoryName( eFactory );
812 else
813 AddURLToStringList( aOpt.GetFactoryEmptyDocumentURL( eFactory ), pRequest->aOpenList );
814 bDocRequestSent = sal_True;
815 }
816 }
817
818 if (!aCmdLineArgs->IsQuickstart() && Desktop::CheckOEM()) {
819 sal_Bool bShowHelp = sal_False;
820 rtl::OUStringBuffer aHelpURLBuffer;
821 if (aCmdLineArgs->IsHelpWriter()) {
822 bShowHelp = sal_True;
823 aHelpURLBuffer.appendAscii("vnd.sun.star.help://swriter/start");
824 } else if (aCmdLineArgs->IsHelpCalc()) {
825 bShowHelp = sal_True;
826 aHelpURLBuffer.appendAscii("vnd.sun.star.help://scalc/start");
827 } else if (aCmdLineArgs->IsHelpDraw()) {
828 bShowHelp = sal_True;
829 aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdraw/start");
830 } else if (aCmdLineArgs->IsHelpImpress()) {
831 bShowHelp = sal_True;
832 aHelpURLBuffer.appendAscii("vnd.sun.star.help://simpress/start");
833 } else if (aCmdLineArgs->IsHelpBase()) {
834 bShowHelp = sal_True;
835 aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdatabase/start");
836 } else if (aCmdLineArgs->IsHelpBasic()) {
837 bShowHelp = sal_True;
838 aHelpURLBuffer.appendAscii("vnd.sun.star.help://sbasic/start");
839 } else if (aCmdLineArgs->IsHelpMath()) {
840 bShowHelp = sal_True;
841 aHelpURLBuffer.appendAscii("vnd.sun.star.help://smath/start");
842 }
843 if (bShowHelp) {
844 Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::LOCALE );
845 rtl::OUString aTmp;
846 aRet >>= aTmp;
847 aHelpURLBuffer.appendAscii("?Language=");
848 aHelpURLBuffer.append(aTmp);
849 #if defined UNX
850 aHelpURLBuffer.appendAscii("&System=UNX");
851 #elif defined WNT
852 aHelpURLBuffer.appendAscii("&System=WIN");
853 #elif defined OS2
854 aHelpURLBuffer.appendAscii("&System=OS2");
855 #endif
856 ApplicationEvent* pAppEvent =
857 new ApplicationEvent( aEmpty, aEmpty,
858 "OPENHELPURL", aHelpURLBuffer.makeStringAndClear());
859 ImplPostForeignAppEvent( pAppEvent );
860 }
861 }
862
863 if ( bDocRequestSent && Desktop::CheckOEM())
864 {
865 // Send requests to dispatch watcher if we have at least one. The receiver
866 // is responsible to delete the request after processing it.
867 if ( aCmdLineArgs->HasModuleParam() )
868 {
869 SvtModuleOptions aOpt;
870
871 // Support command line parameters to start a module (as preselection)
872 if ( aCmdLineArgs->IsWriter() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SWRITER ) )
873 pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_WRITER );
874 else if ( aCmdLineArgs->IsCalc() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SCALC ) )
875 pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_CALC );
876 else if ( aCmdLineArgs->IsImpress() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SIMPRESS ) )
877 pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_IMPRESS );
878 else if ( aCmdLineArgs->IsDraw() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SDRAW ) )
879 pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_DRAW );
880 }
881
882
883 ImplPostProcessDocumentsEvent( pRequest );
884 }
885 else
886 {
887 // delete not used request again
888 delete pRequest;
889 pRequest = NULL;
890 }
891 if (( aArguments.CompareTo( sc_aShowSequence, sc_nShSeqLength ) == COMPARE_EQUAL ) ||
892 aCmdLineArgs->IsEmpty() )
893 {
894 // no document was sent, just bring Office to front
895 ApplicationEvent* pAppEvent =
896 new ApplicationEvent( aEmpty, aEmpty, "APPEAR", aEmpty );
897 ImplPostForeignAppEvent( pAppEvent );
898 }
899
900 // we don't need the mutex any longer...
901 aGuard.clear();
902 // wait for processing to finish
903 if (bDocRequestSent)
904 cProcessed.wait();
905 // processing finished, inform the requesting end
906 nBytes = 0;
907 while (
908 (nResult = maStreamPipe.send(sc_aConfirmationSequence+nBytes, sc_nCSeqLength-nBytes))>0 &&
909 ((nBytes += nResult) < sc_nCSeqLength) ) ;
910 // now we can close, don't we?
911 // maStreamPipe.close();
912
913 }
914 else
915 {
916 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
917 fprintf( stderr, "Error on accept: %d\n", (int)nError );
918 #endif
919 TimeValue tval;
920 tval.Seconds = 1;
921 tval.Nanosec = 0;
922 sleep( tval );
923 }
924 } while( schedule() );
925 }
926
AddToDispatchList(DispatchWatcher::DispatchList & rDispatchList,boost::optional<rtl::OUString> const & cwdUrl,const OUString & aRequestList,DispatchWatcher::RequestType nType,const OUString & aParam,const OUString & aFactory)927 static void AddToDispatchList(
928 DispatchWatcher::DispatchList& rDispatchList,
929 boost::optional< rtl::OUString > const & cwdUrl,
930 const OUString& aRequestList,
931 DispatchWatcher::RequestType nType,
932 const OUString& aParam,
933 const OUString& aFactory )
934 {
935 if ( aRequestList.getLength() > 0 )
936 {
937 sal_Int32 nIndex = 0;
938 do
939 {
940 OUString aToken = aRequestList.getToken( 0, APPEVENT_PARAM_DELIMITER, nIndex );
941 if ( aToken.getLength() > 0 )
942 rDispatchList.push_back(
943 DispatchWatcher::DispatchRequest( nType, aToken, cwdUrl, aParam, aFactory ));
944 }
945 while ( nIndex >= 0 );
946 }
947 }
948
ExecuteCmdLineRequests(ProcessDocumentsRequest & aRequest)949 sal_Bool OfficeIPCThread::ExecuteCmdLineRequests( ProcessDocumentsRequest& aRequest )
950 {
951 // protect the dispatch list
952 osl::ClearableMutexGuard aGuard( GetMutex() );
953
954 static DispatchWatcher::DispatchList aDispatchList;
955
956 rtl::OUString aEmpty;
957 // Create dispatch list for dispatch watcher
958 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aOpenList, DispatchWatcher::REQUEST_OPEN, aEmpty, aRequest.aModule );
959 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aViewList, DispatchWatcher::REQUEST_VIEW, aEmpty, aRequest.aModule );
960 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aStartList, DispatchWatcher::REQUEST_START, aEmpty, aRequest.aModule );
961 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintList, DispatchWatcher::REQUEST_PRINT, aEmpty, aRequest.aModule );
962 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintToList, DispatchWatcher::REQUEST_PRINTTO, aRequest.aPrinterName, aRequest.aModule );
963 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceOpenList, DispatchWatcher::REQUEST_FORCEOPEN, aEmpty, aRequest.aModule );
964 AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceNewList, DispatchWatcher::REQUEST_FORCENEW, aEmpty, aRequest.aModule );
965
966 sal_Bool bShutdown( sal_False );
967
968 if ( pGlobalOfficeIPCThread )
969 {
970 if( ! pGlobalOfficeIPCThread->AreRequestsEnabled() )
971 return bShutdown;
972
973 pGlobalOfficeIPCThread->mnPendingRequests += aDispatchList.size();
974 if ( !pGlobalOfficeIPCThread->mpDispatchWatcher )
975 {
976 pGlobalOfficeIPCThread->mpDispatchWatcher = DispatchWatcher::GetDispatchWatcher();
977 pGlobalOfficeIPCThread->mpDispatchWatcher->acquire();
978 }
979
980 // copy for execute
981 DispatchWatcher::DispatchList aTempList( aDispatchList );
982 aDispatchList.clear();
983
984 aGuard.clear();
985
986 // Execute dispatch requests
987 bShutdown = pGlobalOfficeIPCThread->mpDispatchWatcher->executeDispatchRequests( aTempList, s_bInEnableRequests );
988
989 // set processed flag
990 if (aRequest.pcProcessed != NULL)
991 aRequest.pcProcessed->set();
992 }
993
994 return bShutdown;
995 }
996
997 }
998