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.activity; 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.Context; 24 import android.content.Intent; 25 import android.content.SharedPreferences; 26 import android.os.Binder; 27 import android.os.IBinder; 28 import android.os.StrictMode; 29 import android.preference.PreferenceManager; 30 31 import com.googlecode.android_scripting.AndroidProxy; 32 import com.googlecode.android_scripting.BaseApplication; 33 import com.googlecode.android_scripting.Constants; 34 import com.googlecode.android_scripting.ForegroundService; 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.interpreter.InterpreterConfiguration; 40 import com.googlecode.android_scripting.interpreter.InterpreterProcess; 41 import com.googlecode.android_scripting.interpreter.shell.ShellInterpreter; 42 43 import org.connectbot.ConsoleActivity; 44 import org.connectbot.service.TerminalManager; 45 46 import java.io.File; 47 import java.lang.ref.WeakReference; 48 import java.net.InetSocketAddress; 49 import java.util.ArrayList; 50 import java.util.List; 51 import java.util.Map; 52 import java.util.concurrent.ConcurrentHashMap; 53 54 /** 55 * A service that allows scripts and the RPC server to run in the background. 56 * 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 final String LOG_TAG = "sl4a"; 65 private volatile int mModCount = 0; 66 private Notification mNotification; 67 private PendingIntent mNotificationPendingIntent; 68 private InterpreterConfiguration mInterpreterConfiguration; 69 70 private volatile WeakReference<InterpreterProcess> mRecentlyKilledProcess; 71 72 private TerminalManager mTerminalManager; 73 74 private SharedPreferences mPreferences = null; 75 private boolean mHide; 76 77 public class LocalBinder extends Binder { 78 public ScriptingLayerService getService() { 79 return ScriptingLayerService.this; 80 } 81 } 82 83 @Override 84 public IBinder onBind(Intent intent) { 85 return mBinder; 86 } 87 88 public ScriptingLayerService() { 89 super(NOTIFICATION_ID); 90 mProcessMap = new ConcurrentHashMap<Integer, InterpreterProcess>(); 91 mBinder = new LocalBinder(); 92 } 93 94 @Override 95 public void onCreate() { 96 super.onCreate(); 97 mInterpreterConfiguration = ((BaseApplication) getApplication()).getInterpreterConfiguration(); 98 mRecentlyKilledProcess = new WeakReference<InterpreterProcess>(null); 99 mTerminalManager = new TerminalManager(this); 100 mPreferences = PreferenceManager.getDefaultSharedPreferences(this); 101 mHide = mPreferences.getBoolean(Constants.HIDE_NOTIFY, false); 102 } 103 104 private void createNotificationChannel() { 105 NotificationManager notificationManager = getNotificationManager(); 106 CharSequence name = getString(R.string.notification_channel_name); 107 String description = getString(R.string.notification_channel_description); 108 int importance = NotificationManager.IMPORTANCE_DEFAULT; 109 NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); 110 channel.setDescription(description); 111 channel.enableLights(false); 112 channel.enableVibration(false); 113 notificationManager.createNotificationChannel(channel); 114 } 115 116 @Override 117 protected Notification createNotification() { 118 Intent notificationIntent = new Intent(this, ScriptingLayerService.class); 119 notificationIntent.setAction(Constants.ACTION_SHOW_RUNNING_SCRIPTS); 120 mNotificationPendingIntent = PendingIntent.getService(this, 0, notificationIntent, 0); 121 122 createNotificationChannel(); 123 Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID); 124 builder.setSmallIcon(R.drawable.sl4a_notification_logo) 125 .setTicker(null) 126 .setWhen(System.currentTimeMillis()) 127 .setContentTitle("SL4A Service") 128 .setContentText("Tap to view running scripts") 129 .setContentIntent(mNotificationPendingIntent); 130 mNotification = builder.build(); 131 mNotification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; 132 return mNotification; 133 } 134 135 private void updateNotification(String tickerText) { 136 if (tickerText.equals(mNotification.tickerText)) { 137 // Consequent notifications with the same ticker-text are displayed without any ticker-text. 138 // This is a way around. Alternatively, we can display process name and port. 139 tickerText = tickerText + " "; 140 } 141 String msg; 142 if (mProcessMap.size() <= 1) { 143 msg = "Tap to view " + Integer.toString(mProcessMap.size()) + " running script"; 144 } else { 145 msg = "Tap to view " + Integer.toString(mProcessMap.size()) + " running scripts"; 146 } 147 Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID); 148 builder.setContentTitle("SL4A Service") 149 .setContentText(msg) 150 .setContentIntent(mNotificationPendingIntent) 151 .setSmallIcon(R.drawable.sl4a_notification_logo, mProcessMap.size()) 152 .setWhen(mNotification.when) 153 .setTicker(tickerText); 154 155 mNotification = builder.build(); 156 getNotificationManager().notify(NOTIFICATION_ID, mNotification); 157 } 158 159 private void startAction(Intent intent, int flags, int startId) { 160 AndroidProxy proxy = null; 161 InterpreterProcess interpreterProcess = null; 162 String errmsg = null; 163 if (intent == null) { 164 } else if (intent.getAction().equals(Constants.ACTION_KILL_ALL)) { 165 killAll(); 166 stopSelf(startId); 167 } else if (intent.getAction().equals(Constants.ACTION_KILL_PROCESS)) { 168 killProcess(intent); 169 if (mProcessMap.isEmpty()) { 170 stopSelf(startId); 171 } 172 } else if (intent.getAction().equals(Constants.ACTION_SHOW_RUNNING_SCRIPTS)) { 173 showRunningScripts(); 174 } else { //We are launching a script of some kind 175 if (intent.getAction().equals(Constants.ACTION_LAUNCH_SERVER)) { 176 proxy = launchServer(intent, false); 177 // TODO(damonkohler): This is just to make things easier. Really, we shouldn't need to start 178 // an interpreter when all we want is a server. 179 interpreterProcess = new InterpreterProcess(new ShellInterpreter(), proxy); 180 interpreterProcess.setName("Server"); 181 } 182 else if (intent.getAction().equals(Constants.ACTION_LAUNCH_FOREGROUND_SCRIPT)) { 183 proxy = launchServer(intent, true); 184 launchTerminal(proxy.getAddress()); 185 try { 186 interpreterProcess = launchScript(intent, proxy); 187 } catch (RuntimeException e) { 188 errmsg = 189 "Unable to run " + intent.getStringExtra(Constants.EXTRA_SCRIPT_PATH) + "\n" 190 + e.getMessage(); 191 interpreterProcess = null; 192 } 193 } else if (intent.getAction().equals(Constants.ACTION_LAUNCH_BACKGROUND_SCRIPT)) { 194 proxy = launchServer(intent, true); 195 interpreterProcess = launchScript(intent, proxy); 196 } else if (intent.getAction().equals(Constants.ACTION_LAUNCH_INTERPRETER)) { 197 proxy = launchServer(intent, true); 198 launchTerminal(proxy.getAddress()); 199 interpreterProcess = launchInterpreter(intent, proxy); 200 } 201 if (interpreterProcess == null) { 202 errmsg = "Action not implemented: " + intent.getAction(); 203 } else { 204 addProcess(interpreterProcess); 205 } 206 } 207 if (errmsg != null) { 208 updateNotification(errmsg); 209 } 210 } 211 212 @Override 213 public int onStartCommand(Intent intent, int flags, int startId) { 214 super.onStartCommand(intent, flags, startId); 215 216 //TODO: b/26538940 We need to go back to a strict policy and fix the problems 217 StrictMode.ThreadPolicy sl4aPolicy = new StrictMode.ThreadPolicy.Builder() 218 .detectAll() 219 .penaltyLog() 220 .build(); 221 StrictMode.setThreadPolicy(sl4aPolicy); 222 223 Thread launchThread = new Thread(new Runnable() { 224 public void run() { 225 startAction(intent, flags, startId); 226 } 227 }); 228 launchThread.start(); 229 230 return START_REDELIVER_INTENT; 231 } 232 233 private boolean tryPort(AndroidProxy androidProxy, boolean usePublicIp, int usePort) { 234 if (usePublicIp) { 235 return (androidProxy.startPublic(usePort) != null); 236 } else { 237 return (androidProxy.startLocal(usePort) != null); 238 } 239 } 240 241 private AndroidProxy launchServer(Intent intent, boolean requiresHandshake) { 242 AndroidProxy androidProxy = new AndroidProxy(this, intent, requiresHandshake); 243 boolean usePublicIp = intent.getBooleanExtra(Constants.EXTRA_USE_EXTERNAL_IP, false); 244 int usePort = intent.getIntExtra(Constants.EXTRA_USE_SERVICE_PORT, 0); 245 // If port is in use, fall back to default behaviour 246 if (!tryPort(androidProxy, usePublicIp, usePort)) { 247 if (usePort != 0) { 248 tryPort(androidProxy, usePublicIp, 0); 249 } 250 } 251 return androidProxy; 252 } 253 254 private ScriptProcess launchScript(Intent intent, AndroidProxy proxy) { 255 final int port = proxy.getAddress().getPort(); 256 File script = new File(intent.getStringExtra(Constants.EXTRA_SCRIPT_PATH)); 257 return ScriptLauncher.launchScript(script, mInterpreterConfiguration, proxy, new Runnable() { 258 @Override 259 public void run() { 260 // TODO(damonkohler): This action actually kills the script rather than notifying the 261 // service that script exited on its own. We should distinguish between these two cases. 262 Intent intent = new Intent(ScriptingLayerService.this, ScriptingLayerService.class); 263 intent.setAction(Constants.ACTION_KILL_PROCESS); 264 intent.putExtra(Constants.EXTRA_PROXY_PORT, port); 265 startService(intent); 266 } 267 }); 268 } 269 270 private InterpreterProcess launchInterpreter(Intent intent, AndroidProxy proxy) { 271 InterpreterConfiguration config = 272 ((BaseApplication) getApplication()).getInterpreterConfiguration(); 273 final int port = proxy.getAddress().getPort(); 274 return ScriptLauncher.launchInterpreter(proxy, intent, config, new Runnable() { 275 @Override 276 public void run() { 277 // TODO(damonkohler): This action actually kills the script rather than notifying the 278 // service that script exited on its own. We should distinguish between these two cases. 279 Intent intent = new Intent(ScriptingLayerService.this, ScriptingLayerService.class); 280 intent.setAction(Constants.ACTION_KILL_PROCESS); 281 intent.putExtra(Constants.EXTRA_PROXY_PORT, port); 282 startService(intent); 283 } 284 }); 285 } 286 287 private void launchTerminal(InetSocketAddress address) { 288 Intent i = new Intent(this, ConsoleActivity.class); 289 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 290 i.putExtra(Constants.EXTRA_PROXY_PORT, address.getPort()); 291 startActivity(i); 292 } 293 294 private void showRunningScripts() { 295 Intent i = new Intent(this, ScriptProcessMonitor.class); 296 i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 297 startActivity(i); 298 } 299 300 private void addProcess(InterpreterProcess process) { 301 synchronized(mProcessMap) { 302 mProcessMap.put(process.getPort(), process); 303 mModCount++; 304 } 305 if (!mHide) { 306 updateNotification(process.getName() + " started."); 307 } 308 } 309 310 private InterpreterProcess removeProcess(int port) { 311 InterpreterProcess process; 312 synchronized(mProcessMap) { 313 process = mProcessMap.remove(port); 314 if (process == null) { 315 return null; 316 } 317 mModCount++; 318 } 319 if (!mHide) { 320 updateNotification(process.getName() + " exited."); 321 } 322 return process; 323 } 324 325 private void killProcess(Intent intent) { 326 int processId = intent.getIntExtra(Constants.EXTRA_PROXY_PORT, 0); 327 InterpreterProcess process = removeProcess(processId); 328 if (process != null) { 329 process.kill(); 330 mRecentlyKilledProcess = new WeakReference<InterpreterProcess>(process); 331 } 332 } 333 334 public int getModCount() { 335 return mModCount; 336 } 337 338 private void killAll() { 339 for (InterpreterProcess process : getScriptProcessesList()) { 340 process = removeProcess(process.getPort()); 341 if (process != null) { 342 process.kill(); 343 } 344 } 345 } 346 347 public List<InterpreterProcess> getScriptProcessesList() { 348 ArrayList<InterpreterProcess> result = new ArrayList<InterpreterProcess>(); 349 result.addAll(mProcessMap.values()); 350 return result; 351 } 352 353 public InterpreterProcess getProcess(int port) { 354 InterpreterProcess p = mProcessMap.get(port); 355 if (p == null) { 356 return mRecentlyKilledProcess.get(); 357 } 358 return p; 359 } 360 361 public TerminalManager getTerminalManager() { 362 return mTerminalManager; 363 } 364 } 365