1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.googlecode.android_scripting.service; 18 19 import android.app.Notification; 20 import android.app.NotificationChannel; 21 import android.app.NotificationManager; 22 import android.app.PendingIntent; 23 import android.content.Intent; 24 import android.content.SharedPreferences; 25 import android.os.Binder; 26 import android.os.IBinder; 27 import android.os.StrictMode; 28 import android.preference.PreferenceManager; 29 30 import com.googlecode.android_scripting.AndroidProxy; 31 import com.googlecode.android_scripting.BaseApplication; 32 import com.googlecode.android_scripting.Constants; 33 import com.googlecode.android_scripting.ForegroundService; 34 import com.googlecode.android_scripting.Log; 35 import com.googlecode.android_scripting.NotificationIdFactory; 36 import com.googlecode.android_scripting.R; 37 import com.googlecode.android_scripting.ScriptLauncher; 38 import com.googlecode.android_scripting.ScriptProcess; 39 import com.googlecode.android_scripting.activity.ScriptProcessMonitor; 40 import com.googlecode.android_scripting.interpreter.InterpreterConfiguration; 41 import com.googlecode.android_scripting.interpreter.InterpreterProcess; 42 import com.googlecode.android_scripting.interpreter.shell.ShellInterpreter; 43 44 import org.connectbot.ConsoleActivity; 45 import org.connectbot.service.TerminalManager; 46 47 import java.io.File; 48 import java.lang.ref.WeakReference; 49 import java.net.InetSocketAddress; 50 import java.util.ArrayList; 51 import java.util.List; 52 import java.util.Map; 53 import java.util.concurrent.ConcurrentHashMap; 54 55 /** 56 * A service that allows scripts and the RPC server to run in the background. 57 */ 58 public class ScriptingLayerService extends ForegroundService { 59 private static final int NOTIFICATION_ID = NotificationIdFactory.create(); 60 61 private final IBinder mBinder; 62 private final Map<Integer, InterpreterProcess> mProcessMap; 63 private static final String CHANNEL_ID = "scripting_layer_service_channel"; 64 private volatile int mModCount = 0; 65 private Notification mNotification; 66 private PendingIntent mNotificationPendingIntent; 67 private InterpreterConfiguration mInterpreterConfiguration; 68 69 private volatile WeakReference<InterpreterProcess> mRecentlyKilledProcess; 70 71 private TerminalManager mTerminalManager; 72 73 private SharedPreferences mPreferences = null; 74 private boolean mHide; 75 76 /** 77 * A binder object that contains a reference to the ScriptingLayerService. 78 */ 79 public class LocalBinder extends Binder { getService()80 public ScriptingLayerService getService() { 81 return ScriptingLayerService.this; 82 } 83 } 84 85 @Override onBind(Intent intent)86 public IBinder onBind(Intent intent) { 87 return mBinder; 88 } 89 ScriptingLayerService()90 public ScriptingLayerService() { 91 super(NOTIFICATION_ID); 92 mProcessMap = new ConcurrentHashMap<>(); 93 mBinder = new LocalBinder(); 94 } 95 96 @Override onCreate()97 public void onCreate() { 98 super.onCreate(); 99 mInterpreterConfiguration = ((BaseApplication) getApplication()) 100 .getInterpreterConfiguration(); 101 mRecentlyKilledProcess = new WeakReference<>(null); 102 mTerminalManager = new TerminalManager(this); 103 mPreferences = PreferenceManager.getDefaultSharedPreferences(this); 104 mHide = mPreferences.getBoolean(Constants.HIDE_NOTIFY, false); 105 } 106 createNotificationChannel()107 private void createNotificationChannel() { 108 NotificationManager notificationManager = getNotificationManager(); 109 CharSequence name = getString(R.string.notification_channel_name); 110 String description = getString(R.string.notification_channel_description); 111 int importance = NotificationManager.IMPORTANCE_DEFAULT; 112 NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); 113 channel.setDescription(description); 114 channel.enableLights(false); 115 channel.enableVibration(false); 116 notificationManager.createNotificationChannel(channel); 117 } 118 119 @Override createNotification()120 protected Notification createNotification() { 121 Intent notificationIntent = new Intent(this, ScriptingLayerService.class); 122 notificationIntent.setAction(Constants.ACTION_SHOW_RUNNING_SCRIPTS); 123 mNotificationPendingIntent = PendingIntent.getService(this, 0, notificationIntent, 0); 124 125 createNotificationChannel(); 126 Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID); 127 builder.setSmallIcon(R.drawable.sl4a_notification_logo) 128 .setTicker(null) 129 .setWhen(System.currentTimeMillis()) 130 .setContentTitle("SL4A Service") 131 .setContentText("Tap to view running scripts") 132 .setContentIntent(mNotificationPendingIntent); 133 mNotification = builder.build(); 134 mNotification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; 135 return mNotification; 136 } 137 updateNotification(String tickerText)138 private void updateNotification(String tickerText) { 139 if (tickerText.equals(mNotification.tickerText)) { 140 // Consequent notifications with the same ticker-text are displayed without any 141 // ticker-text. This is a way around. Alternatively, we can display process name and 142 // port. 143 tickerText = tickerText + " "; 144 } 145 String msg; 146 if (mProcessMap.size() <= 1) { 147 msg = "Tap to view " + Integer.toString(mProcessMap.size()) + " running script"; 148 } else { 149 msg = "Tap to view " + Integer.toString(mProcessMap.size()) + " running scripts"; 150 } 151 Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID); 152 builder.setContentTitle("SL4A Service") 153 .setContentText(msg) 154 .setContentIntent(mNotificationPendingIntent) 155 .setSmallIcon(R.drawable.sl4a_notification_logo, mProcessMap.size()) 156 .setWhen(mNotification.when) 157 .setTicker(tickerText); 158 159 mNotification = builder.build(); 160 getNotificationManager().notify(NOTIFICATION_ID, mNotification); 161 } 162 startAction(Intent intent, int flags, int startId)163 private void startAction(Intent intent, int flags, int startId) { 164 if (intent == null || intent.getAction() == null) { 165 return; 166 } 167 168 AndroidProxy proxy; 169 InterpreterProcess interpreterProcess = null; 170 String errmsg = null; 171 Log.d(String.format("Received intent: %s", intent.toUri(0))); 172 173 if (intent.getAction().equals(Constants.ACTION_KILL_ALL)) { 174 killAll(); 175 stopSelf(startId); 176 } else if (intent.getAction().equals(Constants.ACTION_KILL_PROCESS)) { 177 killProcess(intent); 178 if (mProcessMap.isEmpty()) { 179 stopSelf(startId); 180 } 181 } else if (intent.getAction().equals(Constants.ACTION_SHOW_RUNNING_SCRIPTS)) { 182 showRunningScripts(); 183 } else { //We are launching a script of some kind 184 if (intent.getAction().equals(Constants.ACTION_LAUNCH_SERVER)) { 185 proxy = launchServer(intent, false); 186 // TODO(damonkohler): This is just to make things easier. Really, we shouldn't need 187 // to start an interpreter when all we want is a server. 188 interpreterProcess = new InterpreterProcess(new ShellInterpreter(), proxy); 189 interpreterProcess.setName("Server"); 190 } else if (intent.getAction().equals(Constants.ACTION_LAUNCH_FOREGROUND_SCRIPT)) { 191 proxy = launchServer(intent, true); 192 launchTerminal(proxy.getAddress()); 193 try { 194 interpreterProcess = launchScript(intent, proxy); 195 } catch (RuntimeException e) { 196 errmsg = 197 "Unable to run " + intent.getStringExtra(Constants.EXTRA_SCRIPT_PATH) 198 + "\n" + e.getMessage(); 199 interpreterProcess = null; 200 } 201 } else if (intent.getAction().equals(Constants.ACTION_LAUNCH_BACKGROUND_SCRIPT)) { 202 proxy = launchServer(intent, true); 203 interpreterProcess = launchScript(intent, proxy); 204 } else if (intent.getAction().equals(Constants.ACTION_LAUNCH_INTERPRETER)) { 205 proxy = launchServer(intent, true); 206 launchTerminal(proxy.getAddress()); 207 interpreterProcess = launchInterpreter(intent, proxy); 208 } 209 if (interpreterProcess == null) { 210 errmsg = "Action not implemented: " + intent.getAction(); 211 } else { 212 addProcess(interpreterProcess); 213 } 214 } 215 if (errmsg != null) { 216 updateNotification(errmsg); 217 } 218 } 219 220 /** 221 * {@inheritDoc} 222 */ 223 @Override onStartCommand(Intent intent, int flags, int startId)224 public int onStartCommand(Intent intent, int flags, int startId) { 225 super.onStartCommand(intent, flags, startId); 226 StrictMode.ThreadPolicy sl4aPolicy = new StrictMode.ThreadPolicy.Builder() 227 .detectAll() 228 .penaltyLog() 229 .build(); 230 StrictMode.setThreadPolicy(sl4aPolicy); 231 if ((flags & START_FLAG_REDELIVERY) > 0) { 232 Log.w("Intent for action " + intent.getAction() + " has been redelivered."); 233 } 234 // Do the heavy lifting off of the main thread. Prevents jank. 235 new Thread(() -> startAction(intent, flags, startId)).start(); 236 237 return START_REDELIVER_INTENT; 238 } 239 tryPort(AndroidProxy androidProxy, boolean usePublicIp, int usePort)240 private boolean tryPort(AndroidProxy androidProxy, boolean usePublicIp, int usePort) { 241 if (usePublicIp) { 242 return (androidProxy.startPublic(usePort) != null); 243 } else { 244 return (androidProxy.startLocal(usePort) != null); 245 } 246 } 247 launchServer(Intent intent, boolean requiresHandshake)248 private AndroidProxy launchServer(Intent intent, boolean requiresHandshake) { 249 AndroidProxy androidProxy = new AndroidProxy(this, intent, requiresHandshake); 250 boolean usePublicIp = intent.getBooleanExtra(Constants.EXTRA_USE_EXTERNAL_IP, false); 251 int usePort = intent.getIntExtra(Constants.EXTRA_USE_SERVICE_PORT, 0); 252 // If port is in use, fall back to default behaviour 253 if (!tryPort(androidProxy, usePublicIp, usePort)) { 254 if (usePort != 0) { 255 tryPort(androidProxy, usePublicIp, 0); 256 } 257 } 258 return androidProxy; 259 } 260 launchScript(Intent intent, AndroidProxy proxy)261 private ScriptProcess launchScript(Intent intent, AndroidProxy proxy) { 262 final int port = proxy.getAddress().getPort(); 263 File script = new File(intent.getStringExtra(Constants.EXTRA_SCRIPT_PATH)); 264 return ScriptLauncher.launchScript(script, mInterpreterConfiguration, proxy, () -> { 265 // TODO(damonkohler): This action actually kills the script rather than notifying the 266 // service that script exited on its own. We should distinguish between these two cases. 267 Intent newIntent = new Intent(ScriptingLayerService.this, ScriptingLayerService.class); 268 newIntent.setAction(Constants.ACTION_KILL_PROCESS); 269 newIntent.putExtra(Constants.EXTRA_PROXY_PORT, port); 270 Log.i(String.format("Killing process from default shutdownHook: %s", 271 newIntent.toUri(0))); 272 startService(newIntent); 273 }); 274 } 275 launchInterpreter(Intent intent, AndroidProxy proxy)276 private InterpreterProcess launchInterpreter(Intent intent, AndroidProxy proxy) { 277 InterpreterConfiguration config = 278 ((BaseApplication) getApplication()).getInterpreterConfiguration(); 279 final int port = proxy.getAddress().getPort(); 280 return ScriptLauncher.launchInterpreter(proxy, intent, config, () -> { 281 // TODO(damonkohler): This action actually kills the script rather than notifying the 282 // service that script exited on its own. We should distinguish between these two cases. 283 Intent newIntent = new Intent(ScriptingLayerService.this, ScriptingLayerService.class); 284 newIntent.setAction(Constants.ACTION_KILL_PROCESS); 285 newIntent.putExtra(Constants.EXTRA_PROXY_PORT, port); 286 Log.i(String.format("Killing process from default shutdownHook: %s", 287 newIntent.toUri(0))); 288 startService(newIntent); 289 }); 290 } 291 292 private void launchTerminal(InetSocketAddress address) { 293 Intent i = new Intent(this, ConsoleActivity.class); 294 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 295 i.putExtra(Constants.EXTRA_PROXY_PORT, address.getPort()); 296 startActivity(i); 297 } 298 299 private void showRunningScripts() { 300 Intent i = new Intent(this, ScriptProcessMonitor.class); 301 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 302 startActivity(i); 303 } 304 305 private void addProcess(InterpreterProcess process) { 306 synchronized (mProcessMap) { 307 mProcessMap.put(process.getPort(), process); 308 mModCount++; 309 } 310 if (!mHide) { 311 updateNotification(process.getName() + " started."); 312 } 313 } 314 315 private InterpreterProcess removeProcess(int port) { 316 InterpreterProcess process; 317 synchronized (mProcessMap) { 318 process = mProcessMap.remove(port); 319 if (process == null) { 320 return null; 321 } 322 mModCount++; 323 } 324 if (!mHide) { 325 updateNotification(process.getName() + " exited."); 326 } 327 return process; 328 } 329 330 private void killProcess(Intent intent) { 331 int processId = intent.getIntExtra(Constants.EXTRA_PROXY_PORT, 0); 332 InterpreterProcess process = removeProcess(processId); 333 if (process != null) { 334 process.kill(); 335 mRecentlyKilledProcess = new WeakReference<>(process); 336 } 337 } 338 339 public int getModCount() { 340 return mModCount; 341 } 342 343 private void killAll() { 344 for (InterpreterProcess process : getScriptProcessesList()) { 345 process = removeProcess(process.getPort()); 346 if (process != null) { 347 process.kill(); 348 } 349 } 350 } 351 352 /** 353 * Returns the list of all running InterpreterProcesses. This list includes RPC servers. 354 * 355 * @return a list of all running interpreter processes 356 */ 357 public List<InterpreterProcess> getScriptProcessesList() { 358 ArrayList<InterpreterProcess> result = new ArrayList<>(); 359 result.addAll(mProcessMap.values()); 360 return result; 361 } 362 363 /** 364 * Returns the process running on the given port, if any. 365 * 366 * @param port the integer value corresponding to the port to find a process on 367 * @return the InterpreterProcess running on that port, or null 368 */ 369 public InterpreterProcess getProcess(int port) { 370 InterpreterProcess p = mProcessMap.get(port); 371 if (p == null) { 372 return mRecentlyKilledProcess.get(); 373 } 374 return p; 375 } 376 377 public TerminalManager getTerminalManager() { 378 return mTerminalManager; 379 } 380 } 381