summaryrefslogtreecommitdiffstats
path: root/toolkit/components/taskscheduler/TaskSchedulerWinImpl.jsm
blob: ca4ebaa73e623b8a308dc528c1e20e47b6de2774 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var EXPORTED_SYMBOLS = ["_TaskSchedulerWinImpl"];

const { XPCOMUtils } = ChromeUtils.import(
  "resource://gre/modules/XPCOMUtils.jsm"
);

const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");

XPCOMUtils.defineLazyServiceGetters(this, {
  WinTaskSvc: [
    "@mozilla.org/win-task-scheduler-service;1",
    "nsIWinTaskSchedulerService",
  ],
  XreDirProvider: [
    "@mozilla.org/xre/directory-provider;1",
    "nsIXREDirProvider",
  ],
});

XPCOMUtils.defineLazyGlobalGetters(this, ["XMLSerializer"]);

/**
 * Task generation and management for Windows, using Task Scheduler 2.0 (taskschd).
 *
 * Implements the API exposed in TaskScheduler.jsm
 * Not intended for external use, this is in a separate module to ship the code only
 * on Windows, and to expose for testing.
 */
var _TaskSchedulerWinImpl = {
  registerTask(id, command, intervalSeconds, options) {
    // The folder might not yet exist.
    this._createFolderIfNonexistent();

    const xml = this._formatTaskDefinitionXML(
      command,
      intervalSeconds,
      options
    );
    const updateExisting = true;

    WinTaskSvc.registerTask(
      this._taskFolderName(),
      this._formatTaskName(id),
      xml,
      updateExisting
    );
  },

  deleteTask(id) {
    WinTaskSvc.deleteTask(this._taskFolderName(), this._formatTaskName(id));
  },

  deleteAllTasks() {
    const taskFolderName = this._taskFolderName();

    let allTasks;
    try {
      allTasks = WinTaskSvc.getFolderTasks(taskFolderName);
    } catch (ex) {
      if (ex.result == Cr.NS_ERROR_FILE_NOT_FOUND) {
        // Folder doesn't exist, nothing to delete.
        return;
      }
      throw ex;
    }

    const tasksToDelete = allTasks.filter(name => this._matchAppTaskName(name));

    for (const taskName of tasksToDelete) {
      WinTaskSvc.deleteTask(taskFolderName, taskName);
    }

    if (allTasks.length == tasksToDelete.length) {
      // Deleted every task, remove the folder.
      this._deleteFolderIfEmpty();
    }
  },

  _formatTaskDefinitionXML(command, intervalSeconds, options) {
    const startTime = new Date(Date.now() + intervalSeconds * 1000);
    const xmlns = "http://schemas.microsoft.com/windows/2004/02/mit/task";

    // Fill in the constant parts of the task, and those that don't require escaping.
    const docBase = `<Task xmlns="${xmlns}">
  <Triggers>
    <TimeTrigger>
      <StartBoundary>${startTime.toISOString()}</StartBoundary>
      <Repetition>
        <Interval>PT${intervalSeconds}S</Interval>
      </Repetition>
    </TimeTrigger>
  </Triggers>
  <Actions>
    <Exec />
  </Actions>
  <Settings>
    <StartWhenAvailable>true</StartWhenAvailable>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
  </Settings>
  <RegistrationInfo>
     <Author />
  </RegistrationInfo>
</Task>`;
    const doc = new DOMParser().parseFromString(docBase, "text/xml");

    const execAction = doc.querySelector("Actions Exec");

    const commandNode = doc.createElementNS(xmlns, "Command");
    commandNode.textContent = command;
    execAction.appendChild(commandNode);

    if (options?.args) {
      const args = doc.createElementNS(xmlns, "Arguments");
      args.textContent = options.args.map(this._quoteString).join(" ");
      execAction.appendChild(args);
    }

    if (options?.workingDirectory) {
      const workingDirectory = doc.createElementNS(xmlns, "WorkingDirectory");
      workingDirectory.textContent = options.workingDirectory;
      execAction.appendChild(workingDirectory);
    }

    if (options?.disabled) {
      const enabled = doc.createElementNS(xmlns, "Enabled");
      enabled.textContent = "false";
      doc.querySelector("Settings").appendChild(enabled);
    }

    // Other settings to consider for the future:
    // Idle
    // Battery
    // Max run time

    doc.querySelector("RegistrationInfo Author").textContent =
      Services.appinfo.vendor;

    if (options?.description) {
      const registrationInfo = doc.querySelector("RegistrationInfo");
      const description = doc.createElementNS(xmlns, "Description");
      description.textContent = options.description;
      registrationInfo.appendChild(description);
    }

    const serializer = new XMLSerializer();
    return serializer.serializeToString(doc);
  },

  _createFolderIfNonexistent() {
    const { parentName, subName } = this._taskFolderNameParts();

    try {
      WinTaskSvc.createFolder(parentName, subName);
    } catch (e) {
      if (e.result != Cr.NS_ERROR_FILE_ALREADY_EXISTS) {
        throw e;
      }
    }
  },

  _deleteFolderIfEmpty() {
    const { parentName, subName } = this._taskFolderNameParts();

    try {
      WinTaskSvc.deleteFolder(parentName, subName);
    } catch (e) {
      // Missed one somehow, possibly a subfolder?
      if (e.result != Cr.NS_ERROR_FILE_DIR_NOT_EMPTY) {
        throw e;
      }
    }
  },

  /**
   * Quotes a string for use as a single command argument, using Windows quoting
   * conventions.
   *
   * copied from quoteString() in toolkit/modules/subproces/subprocess_worker_win.js
   *
   *
   * @see https://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
   *
   * @param {string} str
   *        The argument string to quote.
   * @returns {string}
   */
  _quoteString(str) {
    if (!/[\s"]/.test(str)) {
      return str;
    }

    let escaped = str.replace(/(\\*)("|$)/g, (m0, m1, m2) => {
      if (m2) {
        m2 = `\\${m2}`;
      }
      return `${m1}${m1}${m2}`;
    });

    return `"${escaped}"`;
  },

  _taskFolderName() {
    return `\\${Services.appinfo.vendor}`;
  },

  _taskFolderNameParts() {
    return {
      parentName: "\\",
      subName: Services.appinfo.vendor,
    };
  },

  _formatTaskName(id) {
    const installHash = XreDirProvider.getInstallHash();
    return `${id} ${installHash}`;
  },

  _matchAppTaskName(name) {
    const installHash = XreDirProvider.getInstallHash();
    return name.endsWith(` ${installHash}`);
  },
};