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:
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 
120     virtual ~Parser() {}
121 
122     virtual boost::optional< rtl::OUString > getCwdUrl() { return m_cwdUrl; }
123 
124     virtual bool next(rtl::OUString * argument) { return next(argument, true); }
125 
126 private:
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 
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 
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 > 0 )
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 
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 
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 
280 void ImplPostForeignAppEvent( ApplicationEvent* pEvent )
281 {
282 	Application::PostUserEvent( STATIC_LINK( NULL, ProcessEventsClass_Impl, CallEvent ), pEvent );
283 }
284 
285 void ImplPostProcessDocumentsEvent( ProcessDocumentsRequest* pEvent )
286 {
287 	Application::PostUserEvent( STATIC_LINK( NULL, ProcessEventsClass_Impl, ProcessDocumentsEvent ), pEvent );
288 }
289 
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
309 OUString SAL_CALL OfficeIPCThreadController::getImplementationName()
310 throw ( RuntimeException )
311 {
312 	return OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.OfficeIPCThreadController" ));
313 }
314 
315 sal_Bool SAL_CALL OfficeIPCThreadController::supportsService( const OUString& )
316 throw ( RuntimeException )
317 {
318 	return sal_False;
319 }
320 
321 Sequence< OUString > SAL_CALL OfficeIPCThreadController::getSupportedServiceNames()
322 throw ( RuntimeException )
323 {
324 	Sequence< OUString > aSeq( 0 );
325 	return aSeq;
326 }
327 
328 // XEventListener
329 void SAL_CALL OfficeIPCThreadController::disposing( const EventObject& )
330 throw( RuntimeException )
331 {
332 }
333 
334 // XTerminateListener
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 
348 void SAL_CALL OfficeIPCThreadController::notifyTermination( const EventObject& )
349 throw( RuntimeException )
350 {
351 }
352 
353 // ----------------------------------------------------------------------------
354 
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 
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 
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 
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 
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 
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 		// Try to create pipe
500 		if ( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Create, rSecurity ))
501 		{
502 			// Pipe created
503 			nPipeMode = PIPEMODE_CREATED;
504 		}
505 		else if( pThread->maPipe.create( pThread->maPipeIdent.getStr(), OPipe::TOption_Open, rSecurity )) // Creation not successfull, now we try to connect
506 		{
507 			// Pipe connected to first office
508 			nPipeMode = PIPEMODE_CONNECTED;
509 		}
510 		else
511 		{
512 			OPipe::TPipeError eReason = pThread->maPipe.getError();
513 			if ((eReason == OPipe::E_ConnectionRefused) || (eReason == OPipe::E_invalidError))
514 				return IPC_STATUS_BOOTSTRAP_ERROR;
515 
516 			// Wait for second office to be ready
517 			TimeValue aTimeValue;
518 			aTimeValue.Seconds = 0;
519 			aTimeValue.Nanosec = 10000000; // 10ms
520 			osl::Thread::wait( aTimeValue );
521 		}
522 
523 	} while ( nPipeMode == PIPEMODE_DONTKNOW );
524 
525 	if ( nPipeMode == PIPEMODE_CREATED )
526 	{
527 		// Seems we are the one and only, so start listening thread
528 		pGlobalOfficeIPCThread = pThread;
529 		pThread->create(); // starts thread
530 	}
531 	else
532 	{
533 		// Seems another office is running. Pipe arguments to it and self terminate
534 		pThread->maStreamPipe = pThread->maPipe;
535 
536 		sal_Bool bWaitBeforeClose = sal_False;
537 		ByteString aArguments(RTL_CONSTASCII_STRINGPARAM(ARGUMENT_PREFIX));
538         rtl::OUString cwdUrl;
539         if (!(tools::getProcessWorkingDir(&cwdUrl) &&
540               addArgument(&aArguments, '1', cwdUrl)))
541         {
542             aArguments += '0';
543         }
544         sal_uInt32 nCount = rtl_getAppCommandArgCount();
545         for( sal_uInt32 i=0; i < nCount; i++ )
546 		{
547 			rtl_getAppCommandArg( i, &aDummy.pData );
548 			if( aDummy.indexOf('-',0) != 0 )
549 			{
550                 bWaitBeforeClose = sal_True;
551 			}
552             if (!addArgument(&aArguments, ',', aDummy)) {
553                 return IPC_STATUS_BOOTSTRAP_ERROR;
554             }
555 		}
556 		// finaly, write the string onto the pipe
557 		pThread->maStreamPipe.write( aArguments.GetBuffer(), aArguments.Len() );
558 		pThread->maStreamPipe.write( "\0", 1 );
559 
560 		// wait for confirmation #95361# #95425#
561 		ByteString aToken(sc_aConfirmationSequence);
562 		char *aReceiveBuffer = new char[aToken.Len()+1];
563 		int n = pThread->maStreamPipe.read( aReceiveBuffer, aToken.Len() );
564 		aReceiveBuffer[n]='\0';
565 
566 		delete pThread;
567 		if (aToken.CompareTo(aReceiveBuffer)!= COMPARE_EQUAL) {
568 			// something went wrong
569 			delete[] aReceiveBuffer;
570 			return IPC_STATUS_BOOTSTRAP_ERROR;
571 		} else {
572 			delete[] aReceiveBuffer;
573 			return IPC_STATUS_2ND_OFFICE;
574 		}
575 	}
576 
577 	return IPC_STATUS_OK;
578 }
579 
580 void OfficeIPCThread::DisableOfficeIPCThread()
581 {
582 	osl::ClearableMutexGuard aMutex( GetMutex() );
583 
584 	if( pGlobalOfficeIPCThread )
585 	{
586         OfficeIPCThread *pOfficeIPCThread = pGlobalOfficeIPCThread;
587 		pGlobalOfficeIPCThread = 0;
588 
589 		// send thread a termination message
590 		// this is done so the subsequent join will not hang
591 		// because the thread hangs in accept of pipe
592         OPipe Pipe( pOfficeIPCThread->maPipeIdent, OPipe::TOption_Open, Security::get() );
593 		//Pipe.send( TERMINATION_SEQUENCE, TERMINATION_LENGTH );
594         if (Pipe.isValid())
595         {
596     		Pipe.send( sc_aTerminationSequence, sc_nTSeqLength+1 ); // also send 0-byte
597 
598 	    	// close the pipe so that the streampipe on the other
599     		// side produces EOF
600 	    	Pipe.close();
601         }
602 
603 		// release mutex to avoid deadlocks
604 		aMutex.clear();
605 
606         OfficeIPCThread::SetReady(pOfficeIPCThread);
607 
608 		// exit gracefully and join
609 		pOfficeIPCThread->join();
610 		delete pOfficeIPCThread;
611 
612 
613 	}
614 }
615 
616 OfficeIPCThread::OfficeIPCThread() :
617 	mbDowning( false ),
618     mbRequestsEnabled( false ),
619 	mnPendingRequests( 0 ),
620 	mpDispatchWatcher( 0 )
621 {
622 }
623 
624 OfficeIPCThread::~OfficeIPCThread()
625 {
626 	::osl::ClearableMutexGuard	aGuard( GetMutex() );
627 
628 	if ( mpDispatchWatcher )
629 		mpDispatchWatcher->release();
630 	maPipe.close();
631 	maStreamPipe.close();
632 	pGlobalOfficeIPCThread = 0;
633 }
634 
635 static void AddURLToStringList( const rtl::OUString& aURL, rtl::OUString& aStringList )
636 {
637 	if ( aStringList.getLength() )
638 		aStringList += ::rtl::OUString::valueOf( (sal_Unicode)APPEVENT_PARAM_DELIMITER );
639 	aStringList += aURL;
640 }
641 
642 void OfficeIPCThread::SetReady(OfficeIPCThread* pThread)
643 {
644     if (pThread == NULL) pThread = pGlobalOfficeIPCThread;
645     if (pThread != NULL)
646     {
647         pThread->cReady.set();
648     }
649 }
650 
651 void SAL_CALL OfficeIPCThread::run()
652 {
653     do
654 	{
655         OPipe::TPipeError
656 			nError = maPipe.accept( maStreamPipe );
657 
658 
659 		if( nError == OStreamPipe::E_None )
660 		{
661 
662             // #111143# and others:
663             // if we receive a request while the office is displaying some dialog or error during
664             // bootstrap, that dialogs event loop might get events that are dispatched by this thread
665             // we have to wait for cReady to be set by the real main loop.
666             // only reqests that dont dispatch events may be processed before cReady is set.
667             cReady.wait();
668 
669             // we might have decided to shutdown while we were sleeping
670             if (!pGlobalOfficeIPCThread) return;
671 
672             // only lock the mutex when processing starts, othewise we deadlock when the office goes
673             // down during wait
674             osl::ClearableMutexGuard aGuard( GetMutex() );
675 
676             ByteString aArguments;
677             // test byte by byte
678             const int nBufSz = 2048;
679             char pBuf[nBufSz];
680             int nBytes = 0;
681             int nResult = 0;
682             // read into pBuf until '\0' is read or read-error
683             while ((nResult=maStreamPipe.recv( pBuf+nBytes, nBufSz-nBytes))>0) {
684 				nBytes += nResult;
685 				if (pBuf[nBytes-1]=='\0') {
686 					aArguments += pBuf;
687 			        break;
688 		        }
689 	        }
690 			// don't close pipe ...
691 
692 			// #90717# Is this a lookup message from another application? if so, ignore
693 			if ( aArguments.Len() == 0 )
694 				continue;
695 
696             // is this a termination message ? if so, terminate
697             if(( aArguments.CompareTo( sc_aTerminationSequence, sc_nTSeqLength ) == COMPARE_EQUAL ) ||
698                     mbDowning ) return;
699             String           aEmpty;
700             std::auto_ptr< CommandLineArgs > aCmdLineArgs;
701             try
702             {
703                 Parser p( aArguments );
704                 aCmdLineArgs.reset( new CommandLineArgs( p ) );
705             }
706             catch ( CommandLineArgs::Supplier::Exception & )
707             {
708 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
709                 fprintf( stderr, "Error in received command line arguments\n" );
710 #endif
711                 continue;
712             }
713             CommandLineArgs	*pCurrentCmdLineArgs = Desktop::GetCommandLineArgs();
714 
715 			if ( aCmdLineArgs->IsQuickstart() )
716 			{
717 				// we have to use application event, because we have to start quickstart service in main thread!!
718 				ApplicationEvent* pAppEvent =
719 					new ApplicationEvent( aEmpty, aEmpty,
720 											"QUICKSTART", aEmpty );
721 				ImplPostForeignAppEvent( pAppEvent );
722 			}
723 
724 			// handle request for acceptor
725 			sal_Bool bAcceptorRequest = sal_False;
726 			OUString aAcceptString;
727             if ( aCmdLineArgs->GetAcceptString(aAcceptString) && Desktop::CheckOEM()) {
728 				ApplicationEvent* pAppEvent =
729 					new ApplicationEvent( aEmpty, aEmpty,
730 										  "ACCEPT", aAcceptString );
731 				ImplPostForeignAppEvent( pAppEvent );
732 				bAcceptorRequest = sal_True;
733 			}
734 			// handle acceptor removal
735 			OUString aUnAcceptString;
736 			if ( aCmdLineArgs->GetUnAcceptString(aUnAcceptString) ) {
737 				ApplicationEvent* pAppEvent =
738 					new ApplicationEvent( aEmpty, aEmpty,
739 										 "UNACCEPT", aUnAcceptString );
740 				ImplPostForeignAppEvent( pAppEvent );
741 				bAcceptorRequest = sal_True;
742 			}
743 
744 #ifndef UNX
745 			// only in non-unix version, we need to handle a -help request
746 			// in a running instance in order to display  the command line help
747 			if ( aCmdLineArgs->IsHelp() ) {
748 				ApplicationEvent* pAppEvent =
749 					new ApplicationEvent( aEmpty, aEmpty, "HELP", aEmpty );
750 				ImplPostForeignAppEvent( pAppEvent );
751 			}
752 #endif
753 
754 			sal_Bool bDocRequestSent = sal_False;
755 			ProcessDocumentsRequest* pRequest = new ProcessDocumentsRequest(
756                 aCmdLineArgs->getCwdUrl());
757             cProcessed.reset();
758             pRequest->pcProcessed = &cProcessed;
759 
760 			// Print requests are not dependent on the -invisible cmdline argument as they are
761 			// loaded with the "hidden" flag! So they are always checked.
762 			bDocRequestSent |= aCmdLineArgs->GetPrintList( pRequest->aPrintList );
763 			bDocRequestSent |= ( aCmdLineArgs->GetPrintToList( pRequest->aPrintToList ) &&
764 									aCmdLineArgs->GetPrinterName( pRequest->aPrinterName )		);
765 
766 			if ( !pCurrentCmdLineArgs->IsInvisible() )
767 			{
768 				// Read cmdline args that can open/create documents. As they would open a window
769 				// they are only allowed if the "-invisible" is currently not used!
770 				bDocRequestSent |= aCmdLineArgs->GetOpenList( pRequest->aOpenList );
771 				bDocRequestSent |= aCmdLineArgs->GetViewList( pRequest->aViewList );
772                 bDocRequestSent |= aCmdLineArgs->GetStartList( pRequest->aStartList );
773 				bDocRequestSent |= aCmdLineArgs->GetForceOpenList( pRequest->aForceOpenList );
774 				bDocRequestSent |= aCmdLineArgs->GetForceNewList( pRequest->aForceNewList );
775 
776 				// Special command line args to create an empty document for a given module
777 
778                 // #i18338# (lo)
779                 // we only do this if no document was specified on the command line,
780                 // since this would be inconsistent with the the behaviour of
781                 // the first process, see OpenClients() (call to OpenDefault()) in app.cxx
782                 if ( aCmdLineArgs->HasModuleParam() && Desktop::CheckOEM() && (!bDocRequestSent))
783 				{
784 					SvtModuleOptions aOpt;
785 					SvtModuleOptions::EFactory eFactory = SvtModuleOptions::E_WRITER;
786 					if ( aCmdLineArgs->IsWriter() )
787 						eFactory = SvtModuleOptions::E_WRITER;
788 					else if ( aCmdLineArgs->IsCalc() )
789 						eFactory = SvtModuleOptions::E_CALC;
790 					else if ( aCmdLineArgs->IsDraw() )
791 						eFactory = SvtModuleOptions::E_DRAW;
792 					else if ( aCmdLineArgs->IsImpress() )
793 						eFactory = SvtModuleOptions::E_IMPRESS;
794 					else if ( aCmdLineArgs->IsBase() )
795 						eFactory = SvtModuleOptions::E_DATABASE;
796 					else if ( aCmdLineArgs->IsMath() )
797 						eFactory = SvtModuleOptions::E_MATH;
798 					else if ( aCmdLineArgs->IsGlobal() )
799 						eFactory = SvtModuleOptions::E_WRITERGLOBAL;
800 					else if ( aCmdLineArgs->IsWeb() )
801 						eFactory = SvtModuleOptions::E_WRITERWEB;
802 
803                     if ( pRequest->aOpenList.getLength() )
804                         pRequest->aModule = aOpt.GetFactoryName( eFactory );
805                     else
806                         AddURLToStringList( aOpt.GetFactoryEmptyDocumentURL( eFactory ), pRequest->aOpenList );
807 					bDocRequestSent = sal_True;
808 				}
809             }
810 
811             if (!aCmdLineArgs->IsQuickstart() && Desktop::CheckOEM()) {
812                 sal_Bool bShowHelp = sal_False;
813                 rtl::OUStringBuffer aHelpURLBuffer;
814                 if (aCmdLineArgs->IsHelpWriter()) {
815                     bShowHelp = sal_True;
816                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://swriter/start");
817                 } else if (aCmdLineArgs->IsHelpCalc()) {
818                     bShowHelp = sal_True;
819                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://scalc/start");
820                 } else if (aCmdLineArgs->IsHelpDraw()) {
821                     bShowHelp = sal_True;
822                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdraw/start");
823                 } else if (aCmdLineArgs->IsHelpImpress()) {
824                     bShowHelp = sal_True;
825                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://simpress/start");
826 				} else if (aCmdLineArgs->IsHelpBase()) {
827                     bShowHelp = sal_True;
828                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sdatabase/start");
829                 } else if (aCmdLineArgs->IsHelpBasic()) {
830                     bShowHelp = sal_True;
831                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://sbasic/start");
832                 } else if (aCmdLineArgs->IsHelpMath()) {
833                     bShowHelp = sal_True;
834                     aHelpURLBuffer.appendAscii("vnd.sun.star.help://smath/start");
835                 }
836                 if (bShowHelp) {
837                     Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::LOCALE );
838                     rtl::OUString aTmp;
839                     aRet >>= aTmp;
840                     aHelpURLBuffer.appendAscii("?Language=");
841                     aHelpURLBuffer.append(aTmp);
842 #if defined UNX
843                     aHelpURLBuffer.appendAscii("&System=UNX");
844 #elif defined WNT
845                     aHelpURLBuffer.appendAscii("&System=WIN");
846 #elif defined OS2
847                     aHelpURLBuffer.appendAscii("&System=OS2");
848 #endif
849                     ApplicationEvent* pAppEvent =
850                         new ApplicationEvent( aEmpty, aEmpty,
851                                               "OPENHELPURL", aHelpURLBuffer.makeStringAndClear());
852                     ImplPostForeignAppEvent( pAppEvent );
853                 }
854             }
855 
856             if ( bDocRequestSent && Desktop::CheckOEM())
857  			{
858 				// Send requests to dispatch watcher if we have at least one. The receiver
859 				// is responsible to delete the request after processing it.
860                 if ( aCmdLineArgs->HasModuleParam() )
861                 {
862                     SvtModuleOptions    aOpt;
863 
864                     // Support command line parameters to start a module (as preselection)
865                     if ( aCmdLineArgs->IsWriter() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SWRITER ) )
866                         pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_WRITER );
867                     else if ( aCmdLineArgs->IsCalc() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SCALC ) )
868                         pRequest->aModule = aOpt.GetFactoryName( SvtModuleOptions::E_CALC );
869                     else if ( aCmdLineArgs->IsImpress() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SIMPRESS ) )
870                         pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_IMPRESS );
871                     else if ( aCmdLineArgs->IsDraw() && aOpt.IsModuleInstalled( SvtModuleOptions::E_SDRAW ) )
872                         pRequest->aModule= aOpt.GetFactoryName( SvtModuleOptions::E_DRAW );
873                 }
874 
875 
876 				ImplPostProcessDocumentsEvent( pRequest );
877 			}
878 			else
879 			{
880 				// delete not used request again
881 				delete pRequest;
882 				pRequest = NULL;
883 			}
884 			if (( aArguments.CompareTo( sc_aShowSequence, sc_nShSeqLength ) == COMPARE_EQUAL ) ||
885 				aCmdLineArgs->IsEmpty() )
886 			{
887 				// no document was sent, just bring Office to front
888 				ApplicationEvent* pAppEvent =
889 						new ApplicationEvent( aEmpty, aEmpty, "APPEAR", aEmpty );
890 				ImplPostForeignAppEvent( pAppEvent );
891 			}
892 
893 			// we don't need the mutex any longer...
894 			aGuard.clear();
895 			// wait for processing to finish
896             if (bDocRequestSent)
897     			cProcessed.wait();
898 			// processing finished, inform the requesting end
899 			nBytes = 0;
900 			while (
901                    (nResult = maStreamPipe.send(sc_aConfirmationSequence+nBytes, sc_nCSeqLength-nBytes))>0 &&
902                    ((nBytes += nResult) < sc_nCSeqLength) ) ;
903 			// now we can close, don't we?
904 			// maStreamPipe.close();
905 
906         }
907         else
908         {
909 #if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
910 			fprintf( stderr, "Error on accept: %d\n", (int)nError );
911 #endif
912 			TimeValue tval;
913 			tval.Seconds = 1;
914 			tval.Nanosec = 0;
915 			sleep( tval );
916 		}
917 	} while( schedule() );
918 }
919 
920 static void AddToDispatchList(
921 	DispatchWatcher::DispatchList& rDispatchList,
922     boost::optional< rtl::OUString > const & cwdUrl,
923 	const OUString& aRequestList,
924 	DispatchWatcher::RequestType nType,
925     const OUString& aParam,
926     const OUString& aFactory )
927 {
928 	if ( aRequestList.getLength() > 0 )
929 	{
930 		sal_Int32 nIndex = 0;
931 		do
932 		{
933 			OUString aToken = aRequestList.getToken( 0, APPEVENT_PARAM_DELIMITER, nIndex );
934 			if ( aToken.getLength() > 0 )
935 				rDispatchList.push_back(
936                     DispatchWatcher::DispatchRequest( nType, aToken, cwdUrl, aParam, aFactory ));
937 		}
938 		while ( nIndex >= 0 );
939 	}
940 }
941 
942 sal_Bool OfficeIPCThread::ExecuteCmdLineRequests( ProcessDocumentsRequest& aRequest )
943 {
944     // protect the dispatch list
945     osl::ClearableMutexGuard aGuard( GetMutex() );
946 
947 	static DispatchWatcher::DispatchList	aDispatchList;
948 
949 	rtl::OUString aEmpty;
950 	// Create dispatch list for dispatch watcher
951     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aOpenList, DispatchWatcher::REQUEST_OPEN, aEmpty, aRequest.aModule );
952     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aViewList, DispatchWatcher::REQUEST_VIEW, aEmpty, aRequest.aModule );
953     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aStartList, DispatchWatcher::REQUEST_START, aEmpty, aRequest.aModule );
954     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintList, DispatchWatcher::REQUEST_PRINT, aEmpty, aRequest.aModule );
955     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aPrintToList, DispatchWatcher::REQUEST_PRINTTO, aRequest.aPrinterName, aRequest.aModule );
956     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceOpenList, DispatchWatcher::REQUEST_FORCEOPEN, aEmpty, aRequest.aModule );
957     AddToDispatchList( aDispatchList, aRequest.aCwdUrl, aRequest.aForceNewList, DispatchWatcher::REQUEST_FORCENEW, aEmpty, aRequest.aModule );
958 
959 	sal_Bool bShutdown( sal_False );
960 
961 	if ( pGlobalOfficeIPCThread )
962 	{
963         if( ! pGlobalOfficeIPCThread->AreRequestsEnabled() )
964             return bShutdown;
965 
966 		pGlobalOfficeIPCThread->mnPendingRequests += aDispatchList.size();
967 		if ( !pGlobalOfficeIPCThread->mpDispatchWatcher )
968 		{
969 			pGlobalOfficeIPCThread->mpDispatchWatcher = DispatchWatcher::GetDispatchWatcher();
970 			pGlobalOfficeIPCThread->mpDispatchWatcher->acquire();
971 		}
972 
973         // copy for execute
974         DispatchWatcher::DispatchList aTempList( aDispatchList );
975         aDispatchList.clear();
976 
977 		aGuard.clear();
978 
979 		// Execute dispatch requests
980 		bShutdown = pGlobalOfficeIPCThread->mpDispatchWatcher->executeDispatchRequests( aTempList, s_bInEnableRequests );
981 
982 		// set processed flag
983 		if (aRequest.pcProcessed != NULL)
984 			aRequest.pcProcessed->set();
985 	}
986 
987 	return bShutdown;
988 }
989 
990 }
991