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