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 throw ( RuntimeException )
311 {
312 	return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.OfficeIPCThreadController" ));
313 }
314 
supportsService(const OUString &)315 sal_Bool SAL_CALL OfficeIPCThreadController::supportsService( const OUString& )
316 throw ( RuntimeException )
317 {
318 	return sal_False;
319 }
320 
getSupportedServiceNames()321 Sequence< OUString > SAL_CALL OfficeIPCThreadController::getSupportedServiceNames()
322 throw ( RuntimeException )
323 {
324 	Sequence< OUString > aSeq( 0 );
325 	return aSeq;
326 }
327 
328 // XEventListener
disposing(const EventObject &)329 void SAL_CALL OfficeIPCThreadController::disposing( const EventObject& )
330 throw( RuntimeException )
331 {
332 }
333 
334 // XTerminateListener
queryTermination(const EventObject &)335 void SAL_CALL OfficeIPCThreadController::queryTermination( const EventObject& )
336 throw( TerminationVetoException, RuntimeException )
337 {
338 	// Desktop ask about pending request through our office ipc pipe. We have to
339 	// be sure that no pending request is waiting because framework is not able to
340 	// handle shutdown and open a document concurrently.
341 
342 	if ( OfficeIPCThread::AreRequestsPending() )
343 		throw TerminationVetoException();
344 	else
345 		OfficeIPCThread::SetDowning();
346 }
347 
notifyTermination(const EventObject &)348 void SAL_CALL OfficeIPCThreadController::notifyTermination( const EventObject& )
349 throw( RuntimeException )
350 {
351 }
352 
353 // ----------------------------------------------------------------------------
354 
GetMutex()355 ::osl::Mutex&	OfficeIPCThread::GetMutex()
356 {
357 	// Get or create our mutex for thread-saftey
358 	if ( !pOfficeIPCThreadMutex )
359 	{
360 		::osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() );
361 		if ( !pOfficeIPCThreadMutex )
362 			pOfficeIPCThreadMutex = new osl::Mutex;
363 	}
364 
365 	return *pOfficeIPCThreadMutex;
366 }
367 
SetDowning()368 void OfficeIPCThread::SetDowning()
369 {
370 	// We have the order to block all incoming requests. Framework
371 	// wants to shutdown and we have to make sure that no loading/printing
372 	// requests are executed anymore.
373 	::osl::MutexGuard	aGuard( GetMutex() );
374 
375 	if ( pGlobalOfficeIPCThread )
376 		pGlobalOfficeIPCThread->mbDowning = true;
377 }
378 
379 static bool s_bInEnableRequests = false;
380 
EnableRequests(bool i_bEnable)381 void OfficeIPCThread::EnableRequests( bool i_bEnable )
382 {
383     // switch between just queueing the requests and executing them
384 	::osl::MutexGuard	aGuard( GetMutex() );
385 
386 	if ( pGlobalOfficeIPCThread )
387     {
388         s_bInEnableRequests = true;
389 		pGlobalOfficeIPCThread->mbRequestsEnabled = i_bEnable;
390         if( i_bEnable )
391         {
392             // hit the compiler over the head
393             ProcessDocumentsRequest aEmptyReq = ProcessDocumentsRequest( boost::optional< rtl::OUString >() );
394             // trigger already queued requests
395             OfficeIPCThread::ExecuteCmdLineRequests( aEmptyReq );
396         }
397         s_bInEnableRequests = false;
398     }
399 }
400 
AreRequestsPending()401 sal_Bool OfficeIPCThread::AreRequestsPending()
402 {
403 	// Give info about pending requests
404 	::osl::MutexGuard	aGuard( GetMutex() );
405 	if ( pGlobalOfficeIPCThread )
406 		return ( pGlobalOfficeIPCThread->mnPendingRequests > 0 );
407 	else
408 		return sal_False;
409 }
410 
RequestsCompleted(int nCount)411 void OfficeIPCThread::RequestsCompleted( int nCount )
412 {
413 	// Remove nCount pending requests from our internal counter
414 	::osl::MutexGuard	aGuard( GetMutex() );
415 	if ( pGlobalOfficeIPCThread )
416 	{
417 		if ( pGlobalOfficeIPCThread->mnPendingRequests > 0 )
418 			pGlobalOfficeIPCThread->mnPendingRequests -= nCount;
419 	}
420 }
421 
EnableOfficeIPCThread()422 OfficeIPCThread::Status OfficeIPCThread::EnableOfficeIPCThread()
423 {
424 	::osl::MutexGuard	aGuard( GetMutex() );
425 
426 	if( pGlobalOfficeIPCThread )
427 		return IPC_STATUS_OK;
428 
429 	::rtl::OUString aUserInstallPath;
430     ::rtl::OUString aDummy;
431 
432 	::vos::OStartupInfo aInfo;
433 	OfficeIPCThread* pThread = new OfficeIPCThread;
434 
435 	pThread->maPipeIdent = OUString( RTL_CONSTASCII_USTRINGPARAM( "SingleOfficeIPC_" ) );
436 
437 	// The name of the named pipe is created with the hashcode of the user installation directory (without /user). We have to retrieve
438 	// this information from a unotools implementation.
439 	::utl::Bootstrap::PathStatus aLocateResult = ::utl::Bootstrap::locateUserInstallation( aUserInstallPath );
440 	if ( aLocateResult == ::utl::Bootstrap::PATH_EXISTS || aLocateResult == ::utl::Bootstrap::PATH_VALID)
441 		aDummy = aUserInstallPath;
442 	else
443 	{
444 		delete pThread;
445 		return IPC_STATUS_BOOTSTRAP_ERROR;
446 	}
447 
448 	// Try to  determine if we are the first office or not! This should prevent multiple
449 	// access to the user directory !
450 	// First we try to create our pipe if this fails we try to connect. We have to do this
451 	// in a loop because the the other office can crash or shutdown between createPipe
452 	// and connectPipe!!
453 
454     OUString            aIniName;
455 
456     aInfo.getExecutableFile( aIniName );
457     sal_uInt32     lastIndex = aIniName.lastIndexOf('/');
458     if ( lastIndex > 0 )
459     {
460         aIniName    = aIniName.copy( 0, lastIndex+1 );
461         aIniName    += OUString( RTL_CONSTASCII_USTRINGPARAM( "perftune" ));
462 #if defined(WNT) || defined(OS2)
463         aIniName    += OUString( RTL_CONSTASCII_USTRINGPARAM( ".ini" ));
464 #else
465         aIniName    += OUString( RTL_CONSTASCII_USTRINGPARAM( "rc" ));
466 #endif
467     }
468 
469 	::rtl::Bootstrap aPerfTuneIniFile( aIniName );
470 
471     OUString aDefault( RTL_CONSTASCII_USTRINGPARAM( "0" ));
472     OUString aPreloadData;
473 
474     aPerfTuneIniFile.getFrom( OUString( RTL_CONSTASCII_USTRINGPARAM( "FastPipeCommunication" )), aPreloadData, aDefault );
475 
476 
477 	OUString aUserInstallPathHashCode;
478 
479     if ( aPreloadData.equalsAscii( "1" ))
480     {
481 		sal_Char	szBuffer[32];
482 		sprintf( szBuffer, "%d", SUPD );
483 		aUserInstallPathHashCode = OUString( szBuffer, strlen(szBuffer), osl_getThreadTextEncoding() );
484     }
485 	else
486 		aUserInstallPathHashCode = CreateMD5FromString( aDummy );
487 
488 
489 	// Check result to create a hash code from the user install path
490 	if ( aUserInstallPathHashCode.getLength() == 0 )
491 		return IPC_STATUS_BOOTSTRAP_ERROR; // Something completely broken, we cannot create a valid hash code!
492 
493 	pThread->maPipeIdent = pThread->maPipeIdent + aUserInstallPathHashCode;
494 
495 	PipeMode nPipeMode = PIPEMODE_DONTKNOW;
496 	do
497 	{
498 		OSecurity &rSecurity = Security::get();
499 		// #119950# Try to connect pipe first. If connected, means another instance already launched.
500 		if( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Open, rSecurity ))
501 		{
502 			// #119950# Test if launched in a new terminal session for same user. On Windows platform, normally a user is resticted
503 			// to have only one terminal session. But if mutiple terminal session for one user is allowed, crash will happen if launched
504 			// OpenOffice from more than one terminal session. So need to detect and prevent this happen.
505 
506 			// Will try to create a same name pipe. If creation is successfully, means current instance is launched in a new session.
507 			vos::OPipe	maSessionPipe;
508 			if ( maSessionPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Create, rSecurity )) {
509 				// Can create a pipe with same name. This can only happen in multiple terminal session environment on Windows platform.
510 				// Will display a warning dialog and exit.
511 				return IPC_STATUS_MULTI_TS_ERROR;
512 			} else {
513 				// Pipe connected to first office
514 				nPipeMode = PIPEMODE_CONNECTED;
515 			}
516 
517 		}
518 		else if ( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Create, rSecurity )) // Connection not successfull, now we try to create
519 		{
520 			// Pipe created
521 			nPipeMode = PIPEMODE_CREATED;
522 		}
523 		else
524 		{
525 			OPipe::TPipeError eReason = pThread->maPipe.getError();
526 			if ((eReason == OPipe::E_ConnectionRefused) || (eReason == OPipe::E_invalidError))
527 				return IPC_STATUS_BOOTSTRAP_ERROR;
528 
529 			// Wait for second office to be ready
530 			TimeValue aTimeValue;
531 			aTimeValue.Seconds = 0;
532 			aTimeValue.Nanosec = 10000000; // 10ms
533 			osl::Thread::wait( aTimeValue );
534 		}
535 
536 	} while ( nPipeMode == PIPEMODE_DONTKNOW );
537 
538 	if ( nPipeMode == PIPEMODE_CREATED )
539 	{
540 		// Seems we are the one and only, so start listening thread
541 		pGlobalOfficeIPCThread = pThread;
542 		pThread->create(); // starts thread
543 	}
544 	else
545 	{
546 		// Seems another office is running. Pipe arguments to it and self terminate
547 		pThread->maStreamPipe = pThread->maPipe;
548 
549 		sal_Bool bWaitBeforeClose = sal_False;
550 		ByteString aArguments(RTL_CONSTASCII_STRINGPARAM(ARGUMENT_PREFIX));
551         rtl::OUString cwdUrl;
552         if (!(tools::getProcessWorkingDir(&cwdUrl) &&
553               addArgument(&aArguments, '1', cwdUrl)))
554         {
555             aArguments += '0';
556         }
557         sal_uInt32 nCount = rtl_getAppCommandArgCount();
558         for( sal_uInt32 i=0; i < nCount; i++ )
559 		{
560 			rtl_getAppCommandArg( i, &aDummy.pData );
561 			if( aDummy.indexOf('-',0) != 0 )
562 			{
563                 bWaitBeforeClose = sal_True;
564 			}
565             if (!addArgument(&aArguments, ',', aDummy)) {
566                 return IPC_STATUS_BOOTSTRAP_ERROR;
567             }
568 		}
569 		// finaly, write the string onto the pipe
570 		pThread->maStreamPipe.write( aArguments.GetBuffer(), aArguments.Len() );
571 		pThread->maStreamPipe.write( "\0", 1 );
572 
573 		// wait for confirmation #95361# #95425#
574 		ByteString aToken(sc_aConfirmationSequence);
575 		char *aReceiveBuffer = new char[aToken.Len()+1];
576 		int n = pThread->maStreamPipe.read( aReceiveBuffer, aToken.Len() );
577 		aReceiveBuffer[n]='\0';
578 
579 		delete pThread;
580 		if (aToken.CompareTo(aReceiveBuffer)!= COMPARE_EQUAL) {
581 			// something went wrong
582 			delete[] aReceiveBuffer;
583 			return IPC_STATUS_BOOTSTRAP_ERROR;
584 		} else {
585 			delete[] aReceiveBuffer;
586 			return IPC_STATUS_2ND_OFFICE;
587 		}
588 	}
589 
590 	return IPC_STATUS_OK;
591 }
592 
DisableOfficeIPCThread()593 void OfficeIPCThread::DisableOfficeIPCThread()
594 {
595 	osl::ClearableMutexGuard aMutex( GetMutex() );
596 
597 	if( pGlobalOfficeIPCThread )
598 	{
599         OfficeIPCThread *pOfficeIPCThread = pGlobalOfficeIPCThread;
600 		pGlobalOfficeIPCThread = 0;
601 
602 		// send thread a termination message
603 		// this is done so the subsequent join will not hang
604 		// because the thread hangs in accept of pipe
605         OPipe Pipe( pOfficeIPCThread->maPipeIdent, OPipe::TOption_Open, Security::get() );
606 		//Pipe.send( TERMINATION_SEQUENCE, TERMINATION_LENGTH );
607         if (Pipe.isValid())
608         {
609     		Pipe.send( sc_aTerminationSequence, sc_nTSeqLength+1 ); // also send 0-byte
610 
611 	    	// close the pipe so that the streampipe on the other
612     		// side produces EOF
613 	    	Pipe.close();
614         }
615 
616 		// release mutex to avoid deadlocks
617 		aMutex.clear();
618 
619         OfficeIPCThread::SetReady(pOfficeIPCThread);
620 
621 		// exit gracefully and join
622 		pOfficeIPCThread->join();
623 		delete pOfficeIPCThread;
624 
625 
626 	}
627 }
628 
OfficeIPCThread()629 OfficeIPCThread::OfficeIPCThread() :
630 	mbDowning( false ),
631     mbRequestsEnabled( false ),
632 	mnPendingRequests( 0 ),
633 	mpDispatchWatcher( 0 )
634 {
635 }
636 
~OfficeIPCThread()637 OfficeIPCThread::~OfficeIPCThread()
638 {
639 	::osl::ClearableMutexGuard	aGuard( GetMutex() );
640 
641 	if ( mpDispatchWatcher )
642 		mpDispatchWatcher->release();
643 	maPipe.close();
644 	maStreamPipe.close();
645 	pGlobalOfficeIPCThread = 0;
646 }
647 
AddURLToStringList(const rtl::OUString & aURL,rtl::OUString & aStringList)648 static void AddURLToStringList( const rtl::OUString& aURL, rtl::OUString& aStringList )
649 {
650 	if ( aStringList.getLength() )
651 		aStringList += ::rtl::OUString::valueOf( (sal_Unicode)APPEVENT_PARAM_DELIMITER );
652 	aStringList += aURL;
653 }
654 
SetReady(OfficeIPCThread * pThread)655 void OfficeIPCThread::SetReady(OfficeIPCThread* pThread)
656 {
657     if (pThread == NULL) pThread = pGlobalOfficeIPCThread;
658     if (pThread != NULL)
659     {
660         pThread->cReady.set();
661     }
662 }
663 
run()664 void SAL_CALL OfficeIPCThread::run()
665 {
666     do
667 	{
668         OPipe::TPipeError
669 			nError = maPipe.accept( maStreamPipe );
670 
671 
672 		if( nError == OStreamPipe::E_None )
673 		{
674 
675             // #111143# and others:
676             // if we receive a request while the office is displaying some dialog or error during
677             // bootstrap, that dialogs event loop might get events that are dispatched by this thread
678             // we have to wait for cReady to be set by the real main loop.
679             // only reqests that dont dispatch events may be processed before cReady is set.
680             cReady.wait();
681 
682             // we might have decided to shutdown while we were sleeping
683             if (!pGlobalOfficeIPCThread) return;
684 
685             // only lock the mutex when processing starts, othewise we deadlock when the office goes
686             // down during wait
687             osl::ClearableMutexGuard aGuard( GetMutex() );
688 
689             ByteString aArguments;
690             // test byte by byte
691             const int nBufSz = 2048;
692             char pBuf[nBufSz];
693             int nBytes = 0;
694             int nResult = 0;
695             // read into pBuf until '\0' is read or read-error
696             while ((nResult=maStreamPipe.recv( pBuf+nBytes, nBufSz-nBytes))>0) {
697 				nBytes += nResult;
698 				if (pBuf[nBytes-1]=='\0') {
699 					aArguments += pBuf;
700 			        break;
701 		        }
702 	        }
703 			// don't close pipe ...
704 
705 			// #90717# Is this a lookup message from another application? if so, ignore
706 			if ( aArguments.Len() == 0 )
707 				continue;
708 
709             // is this a termination message ? if so, terminate
710             if(( aArguments.CompareTo( sc_aTerminationSequence, sc_nTSeqLength ) == COMPARE_EQUAL ) ||
711                     mbDowning ) return;
712             String           aEmpty;
713             std::auto_ptr< CommandLineArgs > aCmdLineArgs;
714             try
715             {
716                 Parser p( aArguments );
717                 aCmdLineArgs.reset( new CommandLineArgs( p ) );
718             }
719             catch ( CommandLineArgs::Supplier::Exception & )
720             {
721 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
722                 fprintf( stderr, "Error in received command line arguments\n" );
723 #endif
724                 continue;
725             }
726             CommandLineArgs	*pCurrentCmdLineArgs = Desktop::GetCommandLineArgs();
727 
728 			if ( aCmdLineArgs->IsQuickstart() )
729 			{
730 				// we have to use application event, because we have to start quickstart service in main thread!!
731 				ApplicationEvent* pAppEvent =
732 					new ApplicationEvent( aEmpty, aEmpty,
733 											"QUICKSTART", aEmpty );
734 				ImplPostForeignAppEvent( pAppEvent );
735 			}
736 
737 			// handle request for acceptor
738 			sal_Bool bAcceptorRequest = sal_False;
739 			OUString aAcceptString;
740             if ( aCmdLineArgs->GetAcceptString(aAcceptString) && Desktop::CheckOEM()) {
741 				ApplicationEvent* pAppEvent =
742 					new ApplicationEvent( aEmpty, aEmpty,
743 										  "ACCEPT", aAcceptString );
744 				ImplPostForeignAppEvent( pAppEvent );
745 				bAcceptorRequest = sal_True;
746 			}
747 			// handle acceptor removal
748 			OUString aUnAcceptString;
749 			if ( aCmdLineArgs->GetUnAcceptString(aUnAcceptString) ) {
750 				ApplicationEvent* pAppEvent =
751 					new ApplicationEvent( aEmpty, aEmpty,
752 										 "UNACCEPT", aUnAcceptString );
753 				ImplPostForeignAppEvent( pAppEvent );
754 				bAcceptorRequest = sal_True;
755 			}
756 
757 #ifndef UNX
758 			// only in non-unix version, we need to handle a -help request
759 			// in a running instance in order to display  the command line help
760 			if ( aCmdLineArgs->IsHelp() ) {
761 				ApplicationEvent* pAppEvent =
762 					new ApplicationEvent( aEmpty, aEmpty, "HELP", aEmpty );
763 				ImplPostForeignAppEvent( pAppEvent );
764 			}
765 #endif
766 
767 			sal_Bool bDocRequestSent = sal_False;
768 			ProcessDocumentsRequest* pRequest = new ProcessDocumentsRequest(
769                 aCmdLineArgs->getCwdUrl());
770             cProcessed.reset();
771             pRequest->pcProcessed = &cProcessed;
772 
773 			// Print requests are not dependent on the -invisible cmdline argument as they are
774 			// loaded with the "hidden" flag! So they are always checked.
775 			bDocRequestSent |= aCmdLineArgs->GetPrintList( pRequest->aPrintList );
776 			bDocRequestSent |= ( aCmdLineArgs->GetPrintToList( pRequest->aPrintToList ) &&
777 									aCmdLineArgs->GetPrinterName( pRequest->aPrinterName )		);
778 
779 			if ( !pCurrentCmdLineArgs->IsInvisible() )
780 			{
781 				// Read cmdline args that can open/create documents. As they would open a window
782 				// they are only allowed if the "-invisible" is currently not used!
783 				bDocRequestSent |= aCmdLineArgs->GetOpenList( pRequest->aOpenList );
784 				bDocRequestSent |= aCmdLineArgs->GetViewList( pRequest->aViewList );
785                 bDocRequestSent |= aCmdLineArgs->GetStartList( pRequest->aStartList );
786 				bDocRequestSent |= aCmdLineArgs->GetForceOpenList( pRequest->aForceOpenList );
787 				bDocRequestSent |= aCmdLineArgs->GetForceNewList( pRequest->aForceNewList );
788 
789 				// Special command line args to create an empty document for a given module
790 
791                 // #i18338# (lo)
792                 // we only do this if no document was specified on the command line,
793                 // since this would be inconsistent with the the behaviour of
794                 // the first process, see OpenClients() (call to OpenDefault()) in app.cxx
795                 if ( aCmdLineArgs->HasModuleParam() && Desktop::CheckOEM() && (!bDocRequestSent))
796 				{
797 					SvtModuleOptions aOpt;
798 					SvtModuleOptions::EFactory eFactory = SvtModuleOptions::E_WRITER;
799 					if ( aCmdLineArgs->IsWriter() )
800 						eFactory = SvtModuleOptions::E_WRITER;
801 					else if ( aCmdLineArgs->IsCalc() )
802 						eFactory = SvtModuleOptions::E_CALC;
803 					else if ( aCmdLineArgs->IsDraw() )
804 						eFactory = SvtModuleOptions::E_DRAW;
805 					else if ( aCmdLineArgs->IsImpress() )
806 						eFactory = SvtModuleOptions::E_IMPRESS;
807 					else if ( aCmdLineArgs->IsBase() )
808 						eFactory = SvtModuleOptions::E_DATABASE;
809 					else if ( aCmdLineArgs->IsMath() )
810 						eFactory = SvtModuleOptions::E_MATH;
811 					else if ( aCmdLineArgs->IsGlobal() )
812 						eFactory = SvtModuleOptions::E_WRITERGLOBAL;
813 					else if ( aCmdLineArgs->IsWeb() )
814 						eFactory = SvtModuleOptions::E_WRITERWEB;
815 
816                     if ( pRequest->aOpenList.getLength() )
817                         pRequest->aModule = aOpt.GetFactoryName( eFactory );
818                     else
819                         AddURLToStringList( aOpt.GetFactoryEmptyDocumentURL( eFactory ), pRequest->aOpenList );
820 					bDocRequestSent = sal_True;
821 				}
822             }
823 
824             if (!aCmdLineArgs->IsQuickstart() && Desktop::CheckOEM()) {
825                 sal_Bool bShowHelp = sal_False;
826                 rtl::OUStringBuffer aHelpURLBuffer;
827                 if (aCmdLineArgs->IsHelpWriter()) {
828                     bShowHelp = sal_True;
829                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://swriter/start");
830                 } else if (aCmdLineArgs->IsHelpCalc()) {
831                     bShowHelp = sal_True;
832                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://scalc/start");
833                 } else if (aCmdLineArgs->IsHelpDraw()) {
834                     bShowHelp = sal_True;
835                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdraw/start");
836                 } else if (aCmdLineArgs->IsHelpImpress()) {
837                     bShowHelp = sal_True;
838                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://simpress/start");
839 				} else if (aCmdLineArgs->IsHelpBase()) {
840                     bShowHelp = sal_True;
841                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdatabase/start");
842                 } else if (aCmdLineArgs->IsHelpBasic()) {
843                     bShowHelp = sal_True;
844                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sbasic/start");
845                 } else if (aCmdLineArgs->IsHelpMath()) {
846                     bShowHelp = sal_True;
847                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://smath/start");
848                 }
849                 if (bShowHelp) {
850                     Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::LOCALE );
851                     rtl::OUString aTmp;
852                     aRet >>= aTmp;
853                     aHelpURLBuffer.appendAscii("?Language=");
854                     aHelpURLBuffer.append(aTmp);
855 #if defined UNX
856                     aHelpURLBuffer.appendAscii("&System=UNX");
857 #elif defined WNT
858                     aHelpURLBuffer.appendAscii("&System=WIN");
859 #elif defined OS2
860                     aHelpURLBuffer.appendAscii("&System=OS2");
861 #endif
862                     ApplicationEvent* pAppEvent =
863                         new ApplicationEvent( aEmpty, aEmpty,
864                                               "OPENHELPURL", aHelpURLBuffer.makeStringAndClear());
865                     ImplPostForeignAppEvent( pAppEvent );
866                 }
867             }
868 
869             if ( bDocRequestSent && Desktop::CheckOEM())
870  			{
871 				// Send requests to dispatch watcher if we have at least one. The receiver
872 				// is responsible to delete the request after processing it.
873                 if ( aCmdLineArgs->HasModuleParam() )
874                 {
875                     SvtModuleOptions    aOpt;
876 
877                     // Support command line parameters to start a module (as preselection)
878                     if ( aCmdLineArgs->IsWriter() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SWRITER ) )
879                         pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_WRITER );
880                     else if ( aCmdLineArgs->IsCalc() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SCALC ) )
881                         pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_CALC );
882                     else if ( aCmdLineArgs->IsImpress() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SIMPRESS ) )
883                         pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_IMPRESS );
884                     else if ( aCmdLineArgs->IsDraw() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SDRAW ) )
885                         pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_DRAW );
886                 }
887 
888 
889 				ImplPostProcessDocumentsEvent( pRequest );
890 			}
891 			else
892 			{
893 				// delete not used request again
894 				delete pRequest;
895 				pRequest = NULL;
896 			}
897 			if (( aArguments.CompareTo( sc_aShowSequence, sc_nShSeqLength ) == COMPARE_EQUAL ) ||
898 				aCmdLineArgs->IsEmpty() )
899 			{
900 				// no document was sent, just bring Office to front
901 				ApplicationEvent* pAppEvent =
902 						new ApplicationEvent( aEmpty, aEmpty, "APPEAR", aEmpty );
903 				ImplPostForeignAppEvent( pAppEvent );
904 			}
905 
906 			// we don't need the mutex any longer...
907 			aGuard.clear();
908 			// wait for processing to finish
909             if (bDocRequestSent)
910     			cProcessed.wait();
911 			// processing finished, inform the requesting end
912 			nBytes = 0;
913 			while (
914                    (nResult = maStreamPipe.send(sc_aConfirmationSequence+nBytes, sc_nCSeqLength-nBytes))>0 &&
915                    ((nBytes += nResult) < sc_nCSeqLength) ) ;
916 			// now we can close, don't we?
917 			// maStreamPipe.close();
918 
919         }
920         else
921         {
922 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
923 			fprintf( stderr, "Error on accept: %d\n", (int)nError );
924 #endif
925 			TimeValue tval;
926 			tval.Seconds = 1;
927 			tval.Nanosec = 0;
928 			sleep( tval );
929 		}
930 	} while( schedule() );
931 }
932 
AddToDispatchList(DispatchWatcher::DispatchList & rDispatchList,boost::optional<rtl::OUString> const & cwdUrl,const OUString & aRequestList,DispatchWatcher::RequestType nType,const OUString & aParam,const OUString & aFactory)933 static void AddToDispatchList(
934 	DispatchWatcher::DispatchList& rDispatchList,
935     boost::optional< rtl::OUString > const & cwdUrl,
936 	const OUString& aRequestList,
937 	DispatchWatcher::RequestType nType,
938     const OUString& aParam,
939     const OUString& aFactory )
940 {
941 	if ( aRequestList.getLength() > 0 )
942 	{
943 		sal_Int32 nIndex = 0;
944 		do
945 		{
946 			OUString aToken = aRequestList.getToken( 0, APPEVENT_PARAM_DELIMITER, nIndex );
947 			if ( aToken.getLength() > 0 )
948 				rDispatchList.push_back(
949                     DispatchWatcher::DispatchRequest( nType, aToken, cwdUrl, aParam, aFactory ));
950 		}
951 		while ( nIndex >= 0 );
952 	}
953 }
954 
ExecuteCmdLineRequests(ProcessDocumentsRequest & aRequest)955 sal_Bool OfficeIPCThread::ExecuteCmdLineRequests( ProcessDocumentsRequest& aRequest )
956 {
957     // protect the dispatch list
958     osl::ClearableMutexGuard aGuard( GetMutex() );
959 
960 	static DispatchWatcher::DispatchList	aDispatchList;
961 
962 	rtl::OUString aEmpty;
963 	// Create dispatch list for dispatch watcher
964     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aOpenList, DispatchWatcher::REQUEST_OPEN, aEmpty, aRequest.aModule );
965     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aViewList, DispatchWatcher::REQUEST_VIEW, aEmpty, aRequest.aModule );
966     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aStartList, DispatchWatcher::REQUEST_START, aEmpty, aRequest.aModule );
967     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintList, DispatchWatcher::REQUEST_PRINT, aEmpty, aRequest.aModule );
968     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintToList, DispatchWatcher::REQUEST_PRINTTO, aRequest.aPrinterName, aRequest.aModule );
969     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceOpenList, DispatchWatcher::REQUEST_FORCEOPEN, aEmpty, aRequest.aModule );
970     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceNewList, DispatchWatcher::REQUEST_FORCENEW, aEmpty, aRequest.aModule );
971 
972 	sal_Bool bShutdown( sal_False );
973 
974 	if ( pGlobalOfficeIPCThread )
975 	{
976         if( ! pGlobalOfficeIPCThread->AreRequestsEnabled() )
977             return bShutdown;
978 
979 		pGlobalOfficeIPCThread->mnPendingRequests += aDispatchList.size();
980 		if ( !pGlobalOfficeIPCThread->mpDispatchWatcher )
981 		{
982 			pGlobalOfficeIPCThread->mpDispatchWatcher = DispatchWatcher::GetDispatchWatcher();
983 			pGlobalOfficeIPCThread->mpDispatchWatcher->acquire();
984 		}
985 
986         // copy for execute
987         DispatchWatcher::DispatchList aTempList( aDispatchList );
988         aDispatchList.clear();
989 
990 		aGuard.clear();
991 
992 		// Execute dispatch requests
993 		bShutdown = pGlobalOfficeIPCThread->mpDispatchWatcher->executeDispatchRequests( aTempList, s_bInEnableRequests );
994 
995 		// set processed flag
996 		if (aRequest.pcProcessed != NULL)
997 			aRequest.pcProcessed->set();
998 	}
999 
1000 	return bShutdown;
1001 }
1002 
1003 }
1004