Line data Source code
1 : /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /*
3 : * This file is part of the LibreOffice project.
4 : *
5 : * This Source Code Form is subject to the terms of the Mozilla Public
6 : * License, v. 2.0. If a copy of the MPL was not distributed with this
7 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 : *
9 : * This file incorporates work covered by the following license notice:
10 : *
11 : * Licensed to the Apache Software Foundation (ASF) under one or more
12 : * contributor license agreements. See the NOTICE file distributed
13 : * with this work for additional information regarding copyright
14 : * ownership. The ASF licenses this file to you under the Apache
15 : * License, Version 2.0 (the "License"); you may not use this file
16 : * except in compliance with the License. You may obtain a copy of
17 : * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 : */
19 :
20 : #include <config_folders.h>
21 :
22 : #include "dp_misc.h"
23 : #include "dp_version.hxx"
24 : #include "dp_interact.h"
25 : #include "rtl/uri.hxx"
26 : #include "rtl/digest.h"
27 : #include "rtl/random.h"
28 : #include "rtl/bootstrap.hxx"
29 : #include "unotools/bootstrap.hxx"
30 : #include "osl/file.hxx"
31 : #include "osl/pipe.hxx"
32 : #include "osl/security.hxx"
33 : #include "osl/thread.hxx"
34 : #include "osl/mutex.hxx"
35 : #include "com/sun/star/ucb/CommandAbortedException.hpp"
36 : #include "com/sun/star/task/XInteractionHandler.hpp"
37 : #include "com/sun/star/bridge/BridgeFactory.hpp"
38 : #include "com/sun/star/bridge/UnoUrlResolver.hpp"
39 : #include "com/sun/star/bridge/XUnoUrlResolver.hpp"
40 : #include "com/sun/star/deployment/ExtensionManager.hpp"
41 : #include "com/sun/star/task/OfficeRestartManager.hpp"
42 : #include "boost/scoped_array.hpp"
43 : #include "boost/shared_ptr.hpp"
44 : #include <comphelper/processfactory.hxx>
45 : #include <salhelper/linkhelper.hxx>
46 :
47 : #ifdef WNT
48 : #define UNICODE
49 : #define WIN32_LEAN_AND_MEAN
50 : #include <windows.h>
51 : #endif
52 :
53 : using namespace ::com::sun::star;
54 : using namespace ::com::sun::star::uno;
55 :
56 : #if defined WNT
57 : #define SOFFICE1 "soffice.exe"
58 : #define SBASE "sbase.exe"
59 : #define SCALC "scalc.exe"
60 : #define SDRAW "sdraw.exe"
61 : #define SIMPRESS "simpress.exe"
62 : #define SWRITER "swriter.exe"
63 : #endif
64 :
65 : #ifdef MACOSX
66 : #define SOFFICE2 "soffice"
67 : #else
68 : #define SOFFICE2 "soffice.bin"
69 : #endif
70 :
71 : namespace dp_misc {
72 : namespace {
73 :
74 : struct UnoRc : public rtl::StaticWithInit<
75 : boost::shared_ptr<rtl::Bootstrap>, UnoRc> {
76 0 : const boost::shared_ptr<rtl::Bootstrap> operator () () {
77 0 : OUString unorc( "$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("uno") );
78 0 : ::rtl::Bootstrap::expandMacros( unorc );
79 : ::boost::shared_ptr< ::rtl::Bootstrap > ret(
80 0 : new ::rtl::Bootstrap( unorc ) );
81 : OSL_ASSERT( ret->getHandle() != 0 );
82 0 : return ret;
83 : }
84 : };
85 :
86 : struct OfficePipeId : public rtl::StaticWithInit<OUString, OfficePipeId> {
87 : const OUString operator () ();
88 : };
89 :
90 0 : const OUString OfficePipeId::operator () ()
91 : {
92 0 : OUString userPath;
93 : ::utl::Bootstrap::PathStatus aLocateResult =
94 0 : ::utl::Bootstrap::locateUserInstallation( userPath );
95 0 : if (!(aLocateResult == ::utl::Bootstrap::PATH_EXISTS ||
96 0 : aLocateResult == ::utl::Bootstrap::PATH_VALID))
97 : {
98 0 : throw Exception("Extension Manager: Could not obtain path for UserInstallation.", 0);
99 : }
100 :
101 0 : rtlDigest digest = rtl_digest_create( rtl_Digest_AlgorithmMD5 );
102 0 : if (!digest) {
103 0 : throw RuntimeException("cannot get digest rtl_Digest_AlgorithmMD5!", 0 );
104 : }
105 :
106 : sal_uInt8 const * data =
107 0 : reinterpret_cast<sal_uInt8 const *>(userPath.getStr());
108 0 : sal_Size size = (userPath.getLength() * sizeof (sal_Unicode));
109 0 : sal_uInt32 md5_key_len = rtl_digest_queryLength( digest );
110 0 : ::boost::scoped_array<sal_uInt8> md5_buf( new sal_uInt8 [ md5_key_len ] );
111 :
112 0 : rtl_digest_init( digest, data, static_cast<sal_uInt32>(size) );
113 0 : rtl_digest_update( digest, data, static_cast<sal_uInt32>(size) );
114 0 : rtl_digest_get( digest, md5_buf.get(), md5_key_len );
115 0 : rtl_digest_destroy( digest );
116 :
117 : // create hex-value string from the MD5 value to keep
118 : // the string size minimal
119 0 : OUStringBuffer buf;
120 0 : buf.appendAscii( "SingleOfficeIPC_" );
121 0 : for ( sal_uInt32 i = 0; i < md5_key_len; ++i ) {
122 0 : buf.append( static_cast<sal_Int32>(md5_buf[ i ]), 0x10 );
123 : }
124 0 : return buf.makeStringAndClear();
125 : }
126 :
127 0 : bool existsOfficePipe()
128 : {
129 0 : OUString const & pipeId = OfficePipeId::get();
130 0 : if (pipeId.isEmpty())
131 0 : return false;
132 0 : ::osl::Security sec;
133 0 : ::osl::Pipe pipe( pipeId, osl_Pipe_OPEN, sec );
134 0 : return pipe.is();
135 : }
136 :
137 : //get modification time
138 0 : static bool getModifyTimeTargetFile(const OUString &rFileURL, TimeValue &rTime)
139 : {
140 0 : salhelper::LinkResolver aResolver(osl_FileStatus_Mask_ModifyTime);
141 :
142 0 : if (aResolver.fetchFileStatus(rFileURL) != osl::FileBase::E_None)
143 0 : return false;
144 :
145 0 : rTime = aResolver.m_aStatus.getModifyTime();
146 :
147 0 : return true;
148 : }
149 :
150 : //Returns true if the Folder was more recently modified then
151 : //the lastsynchronized file. That is the repository needs to
152 : //be synchronized.
153 0 : bool compareExtensionFolderWithLastSynchronizedFile(
154 : OUString const & folderURL, OUString const & fileURL)
155 : {
156 0 : bool bNeedsSync = false;
157 0 : ::osl::DirectoryItem itemExtFolder;
158 : ::osl::File::RC err1 =
159 0 : ::osl::DirectoryItem::get(folderURL, itemExtFolder);
160 : //If it does not exist, then there is nothing to be done
161 0 : if (err1 == ::osl::File::E_NOENT)
162 : {
163 0 : return false;
164 : }
165 0 : else if (err1 != ::osl::File::E_None)
166 : {
167 : OSL_FAIL("Cannot access extension folder");
168 0 : return true; //sync just in case
169 : }
170 :
171 : //If last synchronized does not exist, then OOo is started for the first time
172 0 : ::osl::DirectoryItem itemFile;
173 0 : ::osl::File::RC err2 = ::osl::DirectoryItem::get(fileURL, itemFile);
174 0 : if (err2 == ::osl::File::E_NOENT)
175 : {
176 0 : return true;
177 :
178 : }
179 0 : else if (err2 != ::osl::File::E_None)
180 : {
181 : OSL_FAIL("Cannot access file lastsynchronized");
182 0 : return true; //sync just in case
183 : }
184 :
185 : //compare the modification time of the extension folder and the last
186 : //modified file
187 : TimeValue timeFolder;
188 0 : if (getModifyTimeTargetFile(folderURL, timeFolder))
189 : {
190 : TimeValue timeFile;
191 0 : if (getModifyTimeTargetFile(fileURL, timeFile))
192 : {
193 0 : if (timeFile.Seconds < timeFolder.Seconds)
194 0 : bNeedsSync = true;
195 : }
196 : else
197 : {
198 : OSL_ASSERT(false);
199 0 : bNeedsSync = true;
200 : }
201 : }
202 : else
203 : {
204 : OSL_ASSERT(false);
205 0 : bNeedsSync = true;
206 : }
207 :
208 0 : return bNeedsSync;
209 : }
210 :
211 0 : bool needToSyncRepository(OUString const & name)
212 : {
213 0 : OUString folder;
214 0 : OUString file;
215 0 : if ( name == "bundled" )
216 : {
217 0 : folder = "$BUNDLED_EXTENSIONS";
218 0 : file = "$BUNDLED_EXTENSIONS_USER/lastsynchronized";
219 : }
220 0 : else if ( name == "shared" )
221 : {
222 0 : folder = "$UNO_SHARED_PACKAGES_CACHE/uno_packages";
223 0 : file = "$SHARED_EXTENSIONS_USER/lastsynchronized";
224 : }
225 : else
226 : {
227 : OSL_ASSERT(false);
228 0 : return true;
229 : }
230 0 : ::rtl::Bootstrap::expandMacros(folder);
231 0 : ::rtl::Bootstrap::expandMacros(file);
232 : return compareExtensionFolderWithLastSynchronizedFile(
233 0 : folder, file);
234 : }
235 :
236 :
237 : } // anon namespace
238 :
239 :
240 :
241 : namespace {
242 0 : inline OUString encodeForRcFile( OUString const & str )
243 : {
244 : // escape $\{} (=> rtl bootstrap files)
245 0 : OUStringBuffer buf;
246 0 : sal_Int32 pos = 0;
247 0 : const sal_Int32 len = str.getLength();
248 0 : for ( ; pos < len; ++pos ) {
249 0 : sal_Unicode c = str[ pos ];
250 0 : switch (c) {
251 : case '$':
252 : case '\\':
253 : case '{':
254 : case '}':
255 0 : buf.append( '\\' );
256 0 : break;
257 : }
258 0 : buf.append( c );
259 : }
260 0 : return buf.makeStringAndClear();
261 : }
262 : }
263 :
264 :
265 0 : OUString makeURL( OUString const & baseURL, OUString const & relPath_ )
266 : {
267 0 : OUStringBuffer buf;
268 0 : if (baseURL.getLength() > 1 && baseURL[ baseURL.getLength() - 1 ] == '/')
269 0 : buf.append( baseURL.copy( 0, baseURL.getLength() - 1 ) );
270 : else
271 0 : buf.append( baseURL );
272 0 : OUString relPath(relPath_);
273 0 : if( relPath.startsWith("/") )
274 0 : relPath = relPath.copy( 1 );
275 0 : if (!relPath.isEmpty())
276 : {
277 0 : buf.append( '/' );
278 0 : if (baseURL.match( "vnd.sun.star.expand:" )) {
279 : // encode for macro expansion: relPath is supposed to have no
280 : // macros, so encode $, {} \ (bootstrap mimic)
281 0 : relPath = encodeForRcFile(relPath);
282 :
283 : // encode once more for vnd.sun.star.expand schema:
284 : // vnd.sun.star.expand:$UNO_...
285 : // will expand to file-url
286 0 : relPath = ::rtl::Uri::encode( relPath, rtl_UriCharClassUric,
287 : rtl_UriEncodeIgnoreEscapes,
288 0 : RTL_TEXTENCODING_UTF8 );
289 : }
290 0 : buf.append( relPath );
291 : }
292 0 : return buf.makeStringAndClear();
293 : }
294 :
295 0 : OUString makeURLAppendSysPathSegment( OUString const & baseURL, OUString const & relPath_ )
296 : {
297 0 : OUString segment = relPath_;
298 : OSL_ASSERT(segment.indexOf(static_cast<sal_Unicode>('/')) == -1);
299 :
300 : ::rtl::Uri::encode(
301 : segment, rtl_UriCharClassPchar, rtl_UriEncodeIgnoreEscapes,
302 0 : RTL_TEXTENCODING_UTF8);
303 0 : return makeURL(baseURL, segment);
304 : }
305 :
306 :
307 :
308 :
309 0 : OUString expandUnoRcTerm( OUString const & term_ )
310 : {
311 0 : OUString term(term_);
312 0 : UnoRc::get()->expandMacrosFrom( term );
313 0 : return term;
314 : }
315 :
316 0 : OUString makeRcTerm( OUString const & url )
317 : {
318 : OSL_ASSERT( url.match( "vnd.sun.star.expand:" ));
319 0 : if (url.match( "vnd.sun.star.expand:" )) {
320 : // cut protocol:
321 0 : OUString rcterm( url.copy( sizeof ("vnd.sun.star.expand:") - 1 ) );
322 : // decode uric class chars:
323 0 : rcterm = ::rtl::Uri::decode(
324 0 : rcterm, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
325 0 : return rcterm;
326 : }
327 : else
328 0 : return url;
329 : }
330 :
331 :
332 0 : OUString expandUnoRcUrl( OUString const & url )
333 : {
334 0 : if (url.match( "vnd.sun.star.expand:" )) {
335 : // cut protocol:
336 0 : OUString rcurl( url.copy( sizeof ("vnd.sun.star.expand:") - 1 ) );
337 : // decode uric class chars:
338 0 : rcurl = ::rtl::Uri::decode(
339 0 : rcurl, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
340 : // expand macro string:
341 0 : UnoRc::get()->expandMacrosFrom( rcurl );
342 0 : return rcurl;
343 : }
344 : else {
345 0 : return url;
346 : }
347 : }
348 :
349 :
350 0 : bool office_is_running()
351 : {
352 : //We need to check if we run within the office process. Then we must not use the pipe, because
353 : //this could cause a deadlock. This is actually a workaround for i82778
354 0 : OUString sFile;
355 0 : oslProcessError err = osl_getExecutableFile(& sFile.pData);
356 0 : bool ret = false;
357 0 : if (osl_Process_E_None == err)
358 : {
359 0 : sFile = sFile.copy(sFile.lastIndexOf('/') + 1);
360 0 : if (
361 : #if defined UNIX
362 : sFile == SOFFICE2
363 : #elif defined WNT
364 : //osl_getExecutableFile should deliver "soffice.bin" on windows
365 : //even if swriter.exe, scalc.exe etc. was started. This is a bug
366 : //in osl_getExecutableFile
367 : sFile == SOFFICE1 || sFile == SOFFICE2 || sFile == SBASE || sFile == SCALC
368 : || sFile == SDRAW || sFile == SIMPRESS || sFile == SWRITER
369 : #else
370 : #error "Unsupported platform"
371 : #endif
372 :
373 : )
374 0 : ret = true;
375 : else
376 0 : ret = existsOfficePipe();
377 : }
378 : else
379 : {
380 : OSL_FAIL("NOT osl_Process_E_None ");
381 : //if osl_getExecutable file than we take the risk of creating a pipe
382 0 : ret = existsOfficePipe();
383 : }
384 0 : return ret;
385 : }
386 :
387 :
388 0 : oslProcess raiseProcess(
389 : OUString const & appURL, Sequence<OUString> const & args )
390 : {
391 0 : ::osl::Security sec;
392 0 : oslProcess hProcess = 0;
393 : oslProcessError rc = osl_executeProcess(
394 : appURL.pData,
395 : reinterpret_cast<rtl_uString **>(
396 0 : const_cast<OUString *>(args.getConstArray()) ),
397 0 : args.getLength(),
398 : osl_Process_DETACHED,
399 : sec.getHandle(),
400 : 0, // => current working dir
401 : 0, 0, // => no env vars
402 0 : &hProcess );
403 :
404 0 : switch (rc) {
405 : case osl_Process_E_None:
406 0 : break;
407 : case osl_Process_E_NotFound:
408 0 : throw RuntimeException( "image not found!", 0 );
409 : case osl_Process_E_TimedOut:
410 0 : throw RuntimeException( "timout occurred!", 0 );
411 : case osl_Process_E_NoPermission:
412 0 : throw RuntimeException( "permission denied!", 0 );
413 : case osl_Process_E_Unknown:
414 0 : throw RuntimeException( "unknown error!", 0 );
415 : case osl_Process_E_InvalidError:
416 : default:
417 0 : throw RuntimeException( "unmapped error!", 0 );
418 : }
419 :
420 0 : return hProcess;
421 : }
422 :
423 :
424 0 : OUString generateRandomPipeId()
425 : {
426 : // compute some good pipe id:
427 0 : static rtlRandomPool s_hPool = rtl_random_createPool();
428 0 : if (s_hPool == 0)
429 0 : throw RuntimeException( "cannot create random pool!?", 0 );
430 : sal_uInt8 bytes[ 32 ];
431 0 : if (rtl_random_getBytes(
432 0 : s_hPool, bytes, ARLEN(bytes) ) != rtl_Random_E_None) {
433 0 : throw RuntimeException( "random pool error!?", 0 );
434 : }
435 0 : OUStringBuffer buf;
436 0 : for ( sal_uInt32 i = 0; i < ARLEN(bytes); ++i ) {
437 0 : buf.append( static_cast<sal_Int32>(bytes[ i ]), 0x10 );
438 : }
439 0 : return buf.makeStringAndClear();
440 : }
441 :
442 :
443 0 : Reference<XInterface> resolveUnoURL(
444 : OUString const & connectString,
445 : Reference<XComponentContext> const & xLocalContext,
446 : AbortChannel * abortChannel )
447 : {
448 : Reference<bridge::XUnoUrlResolver> xUnoUrlResolver(
449 0 : bridge::UnoUrlResolver::create( xLocalContext ) );
450 :
451 0 : for (int i = 0; i <= 20; ++i) // 10 seconds
452 : {
453 0 : if (abortChannel != 0 && abortChannel->isAborted()) {
454 : throw ucb::CommandAbortedException(
455 0 : "abort!", Reference<XInterface>() );
456 : }
457 : try {
458 0 : return xUnoUrlResolver->resolve( connectString );
459 : }
460 0 : catch (const connection::NoConnectException &) {
461 0 : if (i < 20)
462 : {
463 0 : TimeValue tv = { 0 /* secs */, 500000000 /* nanosecs */ };
464 0 : ::osl::Thread::wait( tv );
465 : }
466 0 : else throw;
467 : }
468 : }
469 0 : return 0; // warning C4715
470 : }
471 :
472 : #ifdef WNT
473 : void writeConsoleWithStream(OUString const & sText, HANDLE stream)
474 : {
475 : DWORD nWrittenChars = 0;
476 : WriteFile(stream, sText.getStr(),
477 : sText.getLength() * 2, &nWrittenChars, NULL);
478 : }
479 : #else
480 0 : void writeConsoleWithStream(OUString const & sText, FILE * stream)
481 : {
482 0 : OString s = OUStringToOString(sText, osl_getThreadTextEncoding());
483 0 : fprintf(stream, "%s", s.getStr());
484 0 : fflush(stream);
485 0 : }
486 : #endif
487 :
488 0 : void writeConsole(OUString const & sText)
489 : {
490 : #ifdef WNT
491 : writeConsoleWithStream(sText, GetStdHandle(STD_OUTPUT_HANDLE));
492 : #else
493 0 : writeConsoleWithStream(sText, stdout);
494 : #endif
495 0 : }
496 :
497 0 : void writeConsoleError(OUString const & sText)
498 : {
499 : #ifdef WNT
500 : writeConsoleWithStream(sText, GetStdHandle(STD_ERROR_HANDLE));
501 : #else
502 0 : writeConsoleWithStream(sText, stderr);
503 : #endif
504 0 : }
505 :
506 0 : OUString readConsole()
507 : {
508 : #ifdef WNT
509 : sal_Unicode aBuffer[1024];
510 : DWORD dwRead = 0;
511 : //unopkg.com feeds unopkg.exe with wchar_t|s
512 : if (ReadFile( GetStdHandle(STD_INPUT_HANDLE), &aBuffer, sizeof(aBuffer), &dwRead, NULL ) )
513 : {
514 : OSL_ASSERT((dwRead % 2) == 0);
515 : OUString value( aBuffer, dwRead / 2);
516 : return value.trim();
517 : }
518 : #else
519 : char buf[1024];
520 0 : memset(buf, 0, 1024);
521 : // read one char less so that the last char in buf is always zero
522 0 : if (fgets(buf, 1024, stdin) != NULL)
523 : {
524 0 : OUString value = OStringToOUString(OString(buf), osl_getThreadTextEncoding());
525 0 : return value.trim();
526 : }
527 : #endif
528 0 : return OUString();
529 : }
530 :
531 0 : void TRACE(OUString const & sText)
532 : {
533 : (void) sText;
534 : #if OSL_DEBUG_LEVEL > 1
535 : writeConsole(sText);
536 : #endif
537 0 : }
538 :
539 0 : void syncRepositories(
540 : bool force, Reference<ucb::XCommandEnvironment> const & xCmdEnv)
541 : {
542 0 : OUString sDisable;
543 0 : ::rtl::Bootstrap::get( "DISABLE_EXTENSION_SYNCHRONIZATION", sDisable, OUString() );
544 0 : if (!sDisable.isEmpty())
545 0 : return;
546 :
547 0 : Reference<deployment::XExtensionManager> xExtensionManager;
548 : //synchronize shared before bundled otherewise there are
549 : //more revoke and registration calls.
550 0 : sal_Bool bModified = false;
551 0 : if (force || needToSyncRepository("shared") || needToSyncRepository("bundled"))
552 : {
553 0 : xExtensionManager =
554 : deployment::ExtensionManager::get(
555 0 : comphelper::getProcessComponentContext());
556 :
557 0 : if (xExtensionManager.is())
558 : {
559 0 : bModified = xExtensionManager->synchronize(
560 0 : Reference<task::XAbortChannel>(), xCmdEnv);
561 : }
562 : }
563 :
564 0 : if (bModified)
565 : {
566 0 : Reference<task::XRestartManager> restarter(task::OfficeRestartManager::get(comphelper::getProcessComponentContext()));
567 0 : if (restarter.is())
568 : {
569 : OSL_TRACE( "Request restart for modified extensions manager" );
570 0 : restarter->requestRestart(xCmdEnv.is() ? xCmdEnv->getInteractionHandler() :
571 0 : Reference<task::XInteractionHandler>());
572 0 : }
573 0 : }
574 : }
575 :
576 0 : void disposeBridges(Reference<css::uno::XComponentContext> const & ctx)
577 : {
578 0 : if (!ctx.is())
579 0 : return;
580 :
581 0 : Reference<css::bridge::XBridgeFactory2> bridgeFac( css::bridge::BridgeFactory::create(ctx) );
582 :
583 0 : const Sequence< Reference<css::bridge::XBridge> >seqBridges = bridgeFac->getExistingBridges();
584 0 : for (sal_Int32 i = 0; i < seqBridges.getLength(); i++)
585 : {
586 0 : Reference<css::lang::XComponent> comp(seqBridges[i], UNO_QUERY);
587 0 : if (comp.is())
588 : {
589 : try {
590 0 : comp->dispose();
591 : }
592 0 : catch ( const css::lang::DisposedException& )
593 : {
594 : }
595 : }
596 0 : }
597 : }
598 :
599 : }
600 :
601 : /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|