xref: /aoo42x/main/shell/source/unix/exec/shellexec.cxx (revision f8e2c85a)
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_shell.hxx"
26 #include <osl/diagnose.h>
27 #include <osl/thread.h>
28 #include <osl/process.h>
29 #include <osl/file.hxx>
30 #include <rtl/ustrbuf.hxx>
31 
32 #ifndef _RTL_URI_H_
33 #include <rtl/uri.hxx>
34 #endif
35 #include "shellexec.hxx"
36 #include <com/sun/star/system/SystemShellExecuteFlags.hpp>
37 
38 #include <com/sun/star/util/XMacroExpander.hpp>
39 #include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
40 #include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
41 
42 #include "uno/current_context.hxx"
43 
44 #include <string.h>
45 #include <errno.h>
46 #include <unistd.h>
47 
48 //------------------------------------------------------------------------
49 // namespace directives
50 //------------------------------------------------------------------------
51 
52 using com::sun::star::system::XSystemShellExecute;
53 using com::sun::star::system::SystemShellExecuteException;
54 
55 using rtl::OString;
56 using rtl::OUString;
57 using rtl::OStringBuffer;
58 using rtl::OUStringBuffer;
59 using osl::FileBase;
60 
61 using namespace ::com::sun::star::uno;
62 using namespace ::com::sun::star::lang;
63 using namespace ::com::sun::star::system::SystemShellExecuteFlags;
64 using namespace cppu;
65 
66 //------------------------------------------------------------------------
67 // defines
68 //------------------------------------------------------------------------
69 
70 #define SHELLEXEC_IMPL_NAME  "com.sun.star.comp.system.SystemShellExecute2"
71 
72 //------------------------------------------------------------------------
73 // helper functions
74 //------------------------------------------------------------------------
75 
76 namespace // private
77 {
78     Sequence< OUString > SAL_CALL ShellExec_getSupportedServiceNames()
79     {
80         Sequence< OUString > aRet(1);
81         aRet[0] = OUString::createFromAscii("com.sun.star.sys.shell.SystemShellExecute");
82         return aRet;
83     }
84 }
85 
86 void escapeForShell( rtl::OStringBuffer & rBuffer, const rtl::OString & rURL)
87 {
88     sal_Int32 nmax = rURL.getLength();
89     for(sal_Int32 n=0; n < nmax; ++n)
90     {
91         // escape every non alpha numeric characters (excluding a few "known good") by prepending a '\'
92         sal_Char c = rURL[n];
93 #ifndef OS2 // YD shell does not support escaped chars
94         if( ( c < 'A' || c > 'Z' ) && ( c < 'a' || c > 'z' ) && ( c < '0' || c > '9' )  && c != '/' && c != '.' )
95             rBuffer.append( '\\' );
96 #endif
97 
98         rBuffer.append( c );
99     }
100 }
101 
102 //-----------------------------------------------------------------------------------------
103 //
104 //-----------------------------------------------------------------------------------------
105 
106 ShellExec::ShellExec( const Reference< XComponentContext >& xContext ) :
107     WeakImplHelper2< XSystemShellExecute, XServiceInfo >(),
108     m_xContext(xContext)
109 {
110     try {
111         Reference< XCurrentContext > xCurrentContext(getCurrentContext());
112 
113         if (xCurrentContext.is())
114         {
115             Any aValue = xCurrentContext->getValueByName(
116                 OUString( RTL_CONSTASCII_USTRINGPARAM( "system.desktop-environment" ) ) );
117 
118             OUString aDesktopEnvironment;
119             if (aValue >>= aDesktopEnvironment)
120             {
121                 m_aDesktopEnvironment = OUStringToOString(aDesktopEnvironment, RTL_TEXTENCODING_ASCII_US);
122             }
123         }
124     } catch (RuntimeException e) {
125     }
126 }
127 
128 //-------------------------------------------------
129 //
130 //-------------------------------------------------
131 
132 void SAL_CALL ShellExec::execute( const OUString& aCommand, const OUString& aParameter, sal_Int32 nFlags )
133     throw (IllegalArgumentException, SystemShellExecuteException, RuntimeException)
134 {
135     OStringBuffer aBuffer, aLaunchBuffer;
136 
137     // DESKTOP_LAUNCH, see http://freedesktop.org/pipermail/xdg/2004-August/004489.html
138     static const char *pDesktopLaunch = getenv( "DESKTOP_LAUNCH" );
139 
140     // Check wether aCommand contains a document url or not
141     sal_Int32 nIndex = aCommand.indexOf( OUString( RTL_CONSTASCII_USTRINGPARAM(":/") ) );
142 
143     if( nIndex > 0 || 0 == aCommand.compareToAscii("mailto:", 7) )
144     {
145         // It seems to be a url ..
146         // We need to re-encode file urls because osl_getFileURLFromSystemPath converts
147         // to UTF-8 before encoding non ascii characters, which is not what other apps
148         // expect.
149         OUString aURL(
150             com::sun::star::uri::ExternalUriReferenceTranslator::create(
151                 m_xContext)->translateToExternal(aCommand));
152         if ( aURL.getLength() == 0 && aCommand.getLength() != 0 )
153         {
154             throw RuntimeException(
155                 (OUString(
156                     RTL_CONSTASCII_USTRINGPARAM(
157                         "Cannot translate URI reference to external format: "))
158                  + aCommand),
159                 static_cast< cppu::OWeakObject * >(this));
160         }
161 
162 #ifdef MACOSX
163         aBuffer.append("open");
164 #else
165         // The url launchers are expected to be in the $OOO_BASE_DIR/program
166         // directory:
167         com::sun::star::uno::Reference< com::sun::star::util::XMacroExpander >
168             exp;
169         if (!(m_xContext->getValueByName(
170                   rtl::OUString(
171                       RTL_CONSTASCII_USTRINGPARAM(
172                           "/singletons/com.sun.star.util.theMacroExpander")))
173               >>= exp)
174             || !exp.is())
175         {
176             throw SystemShellExecuteException(
177                 rtl::OUString(
178                     RTL_CONSTASCII_USTRINGPARAM(
179                         "component context fails to supply singleton"
180                         " com.sun.star.util.theMacroExpander of type"
181                         " com.sun.star.util.XMacroExpander")),
182                 static_cast< XSystemShellExecute * >(this), ENOENT);
183         }
184         OUString aProgramURL;
185         try {
186             aProgramURL = exp->expandMacros(
187                 rtl::OUString(
188                     RTL_CONSTASCII_USTRINGPARAM("$OOO_BASE_DIR/program/")));
189         } catch (com::sun::star::lang::IllegalArgumentException &)
190         {
191             throw SystemShellExecuteException(
192                 OUString(RTL_CONSTASCII_USTRINGPARAM("Could not expand $OOO_BASE_DIR path")),
193                 static_cast < XSystemShellExecute * > (this), ENOENT );
194         }
195 
196         OUString aProgram;
197         if ( FileBase::E_None != FileBase::getSystemPathFromFileURL(aProgramURL, aProgram))
198         {
199             throw SystemShellExecuteException(
200                 OUString(RTL_CONSTASCII_USTRINGPARAM("Cound not convert executable path")),
201                 static_cast < XSystemShellExecute * > (this), ENOENT );
202         }
203 
204 #ifdef OS2
205         OStringBuffer aProg = OUStringToOString(aProgram, osl_getThreadTextEncoding());
206         aProg.append("open-url.exe");
207         OString aUrl = OUStringToOString(aURL, osl_getThreadTextEncoding());
208         if ( -1 == spawnl(P_NOWAIT, aProg.getStr(), aProg.getStr(), aUrl.getStr() , NULL) )
209         {
210             int nerr = errno;
211             throw SystemShellExecuteException(OUString::createFromAscii( strerror( nerr ) ),
212                 static_cast < XSystemShellExecute * > (this), nerr );
213         }
214         return;
215 #endif
216 
217         OString aTmp = OUStringToOString(aProgram, osl_getThreadTextEncoding());
218         escapeForShell(aBuffer, aTmp);
219 
220 #ifdef SOLARIS
221         if ( m_aDesktopEnvironment.getLength() == 0 )
222              m_aDesktopEnvironment = OString("GNOME");
223 #endif
224 
225         // Respect the desktop environment - if there is an executable named
226         // <desktop-environement-is>-open-url, pass the url to this one instead
227         // of the default "open-url" script.
228         if ( m_aDesktopEnvironment.getLength() > 0 )
229         {
230             OString aDesktopEnvironment(m_aDesktopEnvironment.toAsciiLowerCase());
231             OStringBuffer aCopy(aTmp);
232 
233             aCopy.append(aDesktopEnvironment);
234             aCopy.append("-open-url");
235 
236             if ( 0 == access( aCopy.getStr(), X_OK) )
237             {
238                 aBuffer.append(aDesktopEnvironment);
239                 aBuffer.append("-");
240 
241                 /* CDE requires file urls to be decoded */
242                 if ( m_aDesktopEnvironment.equals("CDE") && 0 == aURL.compareToAscii("file://", 7) )
243                 {
244                     aURL = rtl::Uri::decode(aURL, rtl_UriDecodeWithCharset, osl_getThreadTextEncoding());
245                 }
246             }
247         }
248 
249         aBuffer.append("open-url");
250 #endif
251         aBuffer.append(" ");
252         escapeForShell(aBuffer, OUStringToOString(aURL, osl_getThreadTextEncoding()));
253 
254         if ( pDesktopLaunch && *pDesktopLaunch )
255         {
256             aLaunchBuffer.append( pDesktopLaunch );
257             aLaunchBuffer.append(" ");
258             escapeForShell(aLaunchBuffer, OUStringToOString(aURL, osl_getThreadTextEncoding()));
259         }
260     } else {
261         escapeForShell(aBuffer, OUStringToOString(aCommand, osl_getThreadTextEncoding()));
262         aBuffer.append(" ");
263         if( nFlags != 42 )
264             escapeForShell(aBuffer, OUStringToOString(aParameter, osl_getThreadTextEncoding()));
265         else
266             aBuffer.append(OUStringToOString(aParameter, osl_getThreadTextEncoding()));
267     }
268 
269     // Prefer DESKTOP_LAUNCH when available
270     if ( aLaunchBuffer.getLength() > 0 )
271     {
272         FILE *pLaunch = popen( aLaunchBuffer.makeStringAndClear().getStr(), "w" );
273         if ( pLaunch != NULL )
274         {
275             if ( 0 == pclose( pLaunch ) )
276                 return;
277         }
278         // Failed, do not try DESKTOP_LAUNCH any more
279         pDesktopLaunch = NULL;
280     }
281 
282     OString cmd = aBuffer.makeStringAndClear();
283     if ( 0 != pclose(popen(cmd.getStr(), "w")) )
284     {
285         int nerr = errno;
286         throw SystemShellExecuteException(OUString::createFromAscii( strerror( nerr ) ),
287             static_cast < XSystemShellExecute * > (this), nerr );
288     }
289 }
290 
291 
292 // -------------------------------------------------
293 // XServiceInfo
294 // -------------------------------------------------
295 
296 OUString SAL_CALL ShellExec::getImplementationName(  )
297     throw( RuntimeException )
298 {
299 	return OUString::createFromAscii( SHELLEXEC_IMPL_NAME );
300 }
301 
302 // -------------------------------------------------
303 //	XServiceInfo
304 // -------------------------------------------------
305 
306 sal_Bool SAL_CALL ShellExec::supportsService( const OUString& ServiceName )
307     throw( RuntimeException )
308 {
309     Sequence < OUString > SupportedServicesNames = ShellExec_getSupportedServiceNames();
310 
311     for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
312         if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
313             return sal_True;
314 
315     return sal_False;
316 }
317 
318 // -------------------------------------------------
319 //	XServiceInfo
320 // -------------------------------------------------
321 
322 Sequence< OUString > SAL_CALL ShellExec::getSupportedServiceNames(	 )
323     throw( RuntimeException )
324 {
325     return ShellExec_getSupportedServiceNames();
326 }
327 
328