Debian Codegraph @

shell/source/unix/exec/shellexec.cxx

raw symbols SCIP
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 <osl/thread.h>
21 #include <osl/file.hxx>
22 #include <rtl/strbuf.hxx>
23 #include <sal/log.hxx>
24
25 #include "shellexec.hxx"
26 #include <com/sun/star/system/SystemShellExecuteException.hpp>
27 #include <com/sun/star/system/SystemShellExecuteFlags.hpp>
28
29 #include <com/sun/star/lang/IllegalArgumentException.hpp>
30 #include <com/sun/star/security/AccessControlException.hpp>
31 #include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
32 #include <com/sun/star/uri/UriReferenceFactory.hpp>
33 #include <cppuhelper/supportsservice.hxx>
34 #include <comphelper/lok.hxx>
35
36 #include <string.h>
37 #include <errno.h>
38
39 #if defined MACOSX
40 #include <sys/stat.h>
41 #endif
42
43 #ifdef EMSCRIPTEN
44 #include <emscripten/threading.h>
45 #include <rtl/uri.hxx>
46 extern void execute_browser(const char* sUrl);
47 #endif
48
49 using com::sun::star::system::XSystemShellExecute;
50 using com::sun::star::system::SystemShellExecuteException;
51
52 using namespace ::com::sun::star::uno;
53 using namespace ::com::sun::star::lang;
54 using namespace ::com::sun::star::system::SystemShellExecuteFlags;
55 using namespace cppu;
56
57 #ifndef EMSCRIPTEN
58 namespace
59 {
60 void escapeForShell( OStringBuffer & rBuffer, const OString & rURL)
61 {
62 sal_Int32 nmax = rURL.getLength();
63 for(sal_Int32 n=0; n < nmax; ++n)
64 {
65 // escape every non alpha numeric characters (excluding a few "known good") by prepending a '\'
66 char c = rURL[n];
67 if( ( c < 'A' || c > 'Z' ) && ( c < 'a' || c > 'z' ) && ( c < '0' || c > '9' ) && c != '/' && c != '.' )
68 rBuffer.append( '\\' );
69
70 rBuffer.append( c );
71 }
72 }
73 }
74 #endif
75
76 ShellExec::ShellExec( const Reference< XComponentContext >& xContext ) :
77 m_xContext(xContext)
78 {
79 }
80
81 void SAL_CALL ShellExec::execute( const OUString& aCommand, const OUString& aParameter, sal_Int32 nFlags )
82 {
83 #ifndef EMSCRIPTEN
84 OStringBuffer aBuffer, aLaunchBuffer;
85
86 if (comphelper::LibreOfficeKit::isActive())
87 {
88 SAL_WARN("shell", "Unusual - shell attempt to launch " << aCommand << " with params " << aParameter << " under lok");
89 return;
90 }
91
92 // DESKTOP_LAUNCH, see http://freedesktop.org/pipermail/xdg/2004-August/004489.html
93 static const char *pDesktopLaunch = getenv( "DESKTOP_LAUNCH" );
94
95 // Check whether aCommand contains an absolute URI reference:
96 css::uno::Reference< css::uri::XUriReference > uri(
97 css::uri::UriReferenceFactory::create(m_xContext)->parse(aCommand));
98 if (uri.is() && uri->isAbsolute())
99 {
100 // It seems to be a URL...
101 // We need to re-encode file urls because osl_getFileURLFromSystemPath converts
102 // to UTF-8 before encoding non ascii characters, which is not what other apps
103 // expect.
104 OUString aURL = css::uri::ExternalUriReferenceTranslator::create(
105 m_xContext)->translateToExternal(aCommand);
106 if ( aURL.isEmpty() && !aCommand.isEmpty() )
107 {
108 throw RuntimeException(
109 "Cannot translate URI reference to external format: "
110 + aCommand,
111 getXWeak());
112 }
113
114 #ifdef MACOSX
115 bool dir = false;
116 if (uri->getScheme().equalsIgnoreAsciiCase("file")) {
117 OUString pathname;
118 auto const e1 = osl::FileBase::getSystemPathFromFileURL(aCommand, pathname);
119 if (e1 != osl::FileBase::E_None) {
120 throw css::lang::IllegalArgumentException(
121 ("XSystemShellExecute.execute, getSystemPathFromFileURL <" + aCommand
122 + "> failed with " + OUString::number(e1)),
123 {}, 0);
124 }
125 OString pathname8;
126 if (!pathname.convertToString(
127 &pathname8, RTL_TEXTENCODING_UTF8,
128 (RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR
129 | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR)))
130 {
131 throw css::lang::IllegalArgumentException(
132 "XSystemShellExecute.execute, cannot convert \"" + pathname + "\" to UTF-8", {},
133 0);
134 }
135 struct stat st;
136 auto const e2 = lstat(pathname8.getStr(), &st);
137 if (e2 != 0) {
138 auto const e3 = errno;
139 SAL_INFO("shell", "lstat(" << pathname8 << ") failed with errno " << e3);
140 }
141 if (e2 != 0) {
142 throw css::lang::IllegalArgumentException(
143 "XSystemShellExecute.execute, cannot process <" + aCommand + ">", {}, 0);
144 } else if (S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode)) {
145 dir = true;
146 } else if ((nFlags & css::system::SystemShellExecuteFlags::URIS_ONLY) != 0
147 && (!S_ISREG(st.st_mode)
148 || (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0))
149 {
150 throw css::security::AccessControlException(
151 "XSystemShellExecute.execute, bad <" + aCommand + ">", {}, {});
152 } else if (pathname.endsWithIgnoreAsciiCase(".class")
153 || pathname.endsWithIgnoreAsciiCase(".dmg")
154 || pathname.endsWithIgnoreAsciiCase(".fileloc")
155 || pathname.endsWithIgnoreAsciiCase(".inetloc")
156 || pathname.endsWithIgnoreAsciiCase(".ipa")
157 || pathname.endsWithIgnoreAsciiCase(".jar")
158 || pathname.endsWithIgnoreAsciiCase(".terminal"))
159 {
160 dir = true;
161 }
162 }
163
164 //TODO: Using open(1) with an argument that syntactically is an absolute
165 // URI reference does not necessarily give expected results:
166 // 1 If the given URI reference matches a supported scheme (e.g.,
167 // "mailto:foo"):
168 // 1.1 If it matches an existing pathname (relative to CWD): Results
169 // in "mailto:foo?\n[0]\tcancel\n[1]\tOpen the file\tmailto:foo\n[2]\t
170 // Open the URL\tmailto:foo\n\nWhich did you mean? Cancelled." on
171 // stderr and SystemShellExecuteException.
172 // 1.2 If it does not match an existing pathname (relative to CWD):
173 // Results in the corresponding application being opened with the given
174 // document (e.g., Mail with a New Message).
175 // 2 If the given URI reference does not match a supported scheme
176 // (e.g., "foo:bar"):
177 // 2.1 If it matches an existing pathname (relative to CWD) pointing to
178 // an executable: Results in execution of that executable.
179 // 2.2 If it matches an existing pathname (relative to CWD) pointing to
180 // a non-executable regular file: Results in opening it in TextEdit.
181 // 2.3 If it matches an existing pathname (relative to CWD) pointing to
182 // a directory: Results in opening it in Finder.
183 // 2.4 If it does not match an existing pathname (relative to CWD):
184 // Results in "The file /.../foo:bar does not exits." (where "/..." is
185 // the CWD) on stderr and SystemShellExecuteException.
186 aBuffer.append("open");
187 if (dir) {
188 aBuffer.append(" -R");
189 }
190 aBuffer.append(" --");
191 #else
192 // Just use xdg-open on non-Mac
193 aBuffer.append("xdg-open");
194 #endif
195 aBuffer.append(" ");
196 escapeForShell(aBuffer, OUStringToOString(aURL, osl_getThreadTextEncoding()));
197
198 if ( pDesktopLaunch && *pDesktopLaunch )
199 {
200 aLaunchBuffer.append( pDesktopLaunch + OString::Concat(" "));
201 escapeForShell(aLaunchBuffer, OUStringToOString(aURL, osl_getThreadTextEncoding()));
202 }
203 } else if ((nFlags & css::system::SystemShellExecuteFlags::URIS_ONLY) != 0)
204 {
205 throw css::lang::IllegalArgumentException(
206 "XSystemShellExecute.execute URIS_ONLY with non-absolute"
207 " URI reference "
208 + aCommand,
209 getXWeak(), 0);
210 } else {
211 #if defined MACOSX
212 auto usingOpen = false;
213 if (OString pathname8;
214 aCommand.convertToString(
215 &pathname8, RTL_TEXTENCODING_UTF8,
216 RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR | RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR))
217 {
218 if (struct stat st; stat(pathname8.getStr(), &st) == 0 && S_ISDIR(st.st_mode)) {
219 usingOpen = true;
220 aBuffer.append("open -a ");
221 }
222 }
223 #endif
224 escapeForShell(aBuffer, OUStringToOString(aCommand, osl_getThreadTextEncoding()));
225 if (!aParameter.isEmpty()) {
226 aBuffer.append(" ");
227 #if defined MACOSX
228 if (usingOpen) {
229 aBuffer.append("--args ");
230 }
231 #endif
232 if( nFlags != 42 )
233 escapeForShell(aBuffer, OUStringToOString(aParameter, osl_getThreadTextEncoding()));
234 else
235 aBuffer.append(OUStringToOString(aParameter, osl_getThreadTextEncoding()));
236 }
237 }
238
239 // Prefer DESKTOP_LAUNCH when available
240 if ( !aLaunchBuffer.isEmpty() )
241 {
242 FILE *pLaunch = popen( aLaunchBuffer.makeStringAndClear().getStr(), "w" );
243 if ( pLaunch != nullptr )
244 {
245 if ( 0 == pclose( pLaunch ) )
246 return;
247 }
248 // Failed, do not try DESKTOP_LAUNCH any more
249 pDesktopLaunch = nullptr;
250 }
251
252 OString cmd =
253 #ifdef LINUX
254 // avoid blocking (call it in background)
255 "( " + aBuffer + " ) &";
256 #else
257 aBuffer.makeStringAndClear();
258 #endif
259 FILE *pLaunch = popen(cmd.getStr(), "w");
260 if ( pLaunch != nullptr )
261 {
262 if ( 0 == pclose( pLaunch ) )
263 return;
264 }
265
266 int nerr = errno;
267 throw SystemShellExecuteException(OUString::createFromAscii( strerror( nerr ) ),
268 static_cast < XSystemShellExecute * > (this), nerr );
269 #else // EMSCRIPTEN
270 (void)nFlags;
271
272 css::uno::Reference< css::uri::XUriReference > uri(
273 css::uri::UriReferenceFactory::create(m_xContext)->parse(aCommand));
274 if (!uri.is() || !uri->isAbsolute())
275 throw SystemShellExecuteException("Emscripten can just open absolute URIs.",
276 static_cast<XSystemShellExecute*>(this), 42);
277 if (!aParameter.isEmpty())
278 throw SystemShellExecuteException("Emscripten can't process parameters; encode in URI.",
279 static_cast<XSystemShellExecute*>(this), 42);
280
281 OUString sEscapedURI(rtl::Uri::encode(aCommand, rtl_UriCharClassUric,
282 rtl_UriEncodeIgnoreEscapes, RTL_TEXTENCODING_UTF8));
283 emscripten_sync_run_in_main_runtime_thread(
284 EM_FUNC_SIG_VI, execute_browser, sEscapedURI.toUtf8().getStr());
285 #endif
286 }
287
288 // XServiceInfo
289
290 OUString SAL_CALL ShellExec::getImplementationName( )
291 {
292 return u"com.sun.star.comp.system.SystemShellExecute"_ustr;
293 }
294
295 sal_Bool SAL_CALL ShellExec::supportsService( const OUString& ServiceName )
296 {
297 return cppu::supportsService(this, ServiceName);
298 }
299
300 Sequence< OUString > SAL_CALL ShellExec::getSupportedServiceNames( )
301 {
302 return { u"com.sun.star.system.SystemShellExecute"_ustr };
303 }
304
305 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
306 shell_ShellExec_get_implementation(
307 css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const&)
308 {
309 return cppu::acquire(new ShellExec(context));
310 }
311
312
313 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */