summaryrefslogtreecommitdiffstats
path: root/toolkit/components/taskscheduler/nsWinTaskScheduler.cpp
blob: 21b2909805afb93a69619c4890d6f590c020b1f0 (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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode:nil; c-basic-offset: 2 -*- */
/* 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/. */

#include "nsWinTaskScheduler.h"

#include <windows.h>
#include <comdef.h>
#include <taskschd.h>

#include "nsString.h"

#include "mozilla/RefPtr.h"
#include "mozilla/ResultVariant.h"

using namespace mozilla;

struct SysFreeStringDeleter {
  void operator()(BSTR aPtr) { ::SysFreeString(aPtr); }
};
using BStrPtr = mozilla::UniquePtr<OLECHAR, SysFreeStringDeleter>;

static nsresult ToNotFoundOrFailure(HRESULT hr) {
  if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
    return NS_ERROR_FILE_NOT_FOUND;
  } else {
    return NS_ERROR_FAILURE;
  }
}

static nsresult ToAlreadyExistsOrFailure(HRESULT hr) {
  if (hr == HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) {
    return NS_ERROR_FILE_ALREADY_EXISTS;
  } else {
    return NS_ERROR_FAILURE;
  }
}

[[nodiscard]] static Result<RefPtr<ITaskFolder>, HRESULT> GetTaskFolder(
    const char16_t* aFolderName) {
  HRESULT hr;
  RefPtr<ITaskService> scheduler = nullptr;

  hr = CoCreateInstance(CLSID_TaskScheduler, nullptr, CLSCTX_INPROC_SERVER,
                        IID_ITaskService, getter_AddRefs(scheduler));
  if (FAILED(hr)) {
    return Err(hr);
  }

  // Connect to the local Task Scheduler.
  hr = scheduler->Connect(VARIANT{}, VARIANT{}, VARIANT{}, VARIANT{});
  if (FAILED(hr)) {
    return Err(hr);
  }

  BStrPtr bstrFolderName =
      BStrPtr(::SysAllocString(reinterpret_cast<const OLECHAR*>(aFolderName)));

  RefPtr<ITaskFolder> folder = nullptr;
  hr = scheduler->GetFolder(bstrFolderName.get(), getter_AddRefs(folder));
  if (FAILED(hr)) {
    return Err(hr);
  }

  return folder;
}

[[nodiscard]] static Result<RefPtr<IRegisteredTask>, HRESULT> GetRegisteredTask(
    const char16_t* aFolderName, const char16_t* aTaskName) {
  auto folder = GetTaskFolder(aFolderName);
  if (!folder.isOk()) {
    return Err(folder.unwrapErr());
  }

  BStrPtr bstrTaskName =
      BStrPtr(::SysAllocString(reinterpret_cast<const OLECHAR*>(aTaskName)));

  RefPtr<IRegisteredTask> task = nullptr;
  HRESULT hr =
      folder.unwrap()->GetTask(bstrTaskName.get(), getter_AddRefs(task));
  if (FAILED(hr)) {
    return Err(hr);
  }

  return task;
}

NS_IMPL_ISUPPORTS(nsWinTaskSchedulerService, nsIWinTaskSchedulerService)

NS_IMETHODIMP
nsWinTaskSchedulerService::GetTaskXML(const char16_t* aFolderName,
                                      const char16_t* aTaskName,
                                      nsAString& aResult) {
  if (!aFolderName || !aTaskName) {
    return NS_ERROR_NULL_POINTER;
  }

  auto task = GetRegisteredTask(aFolderName, aTaskName);
  if (!task.isOk()) {
    return ToNotFoundOrFailure(task.unwrapErr());
  }

  {
    BSTR bstrXml = nullptr;
    if (FAILED(task.unwrap()->get_Xml(&bstrXml))) {
      return NS_ERROR_FAILURE;
    }

    aResult.Assign(bstrXml, ::SysStringLen(bstrXml));
    ::SysFreeString(bstrXml);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::RegisterTask(const char16_t* aFolderName,
                                        const char16_t* aTaskName,
                                        const char16_t* aDefinitionXML,
                                        bool aUpdateExisting) {
  if (!aFolderName || !aTaskName || !aDefinitionXML) {
    return NS_ERROR_NULL_POINTER;
  }

  auto folder = GetTaskFolder(aFolderName);
  if (!folder.isOk()) {
    return ToNotFoundOrFailure(folder.unwrapErr());
  }

  BStrPtr bstrTaskName =
      BStrPtr(::SysAllocString(reinterpret_cast<const OLECHAR*>(aTaskName)));
  BStrPtr bstrXml = BStrPtr(
      ::SysAllocString(reinterpret_cast<const OLECHAR*>(aDefinitionXML)));
  LONG flags = aUpdateExisting ? TASK_CREATE_OR_UPDATE : TASK_CREATE;
  TASK_LOGON_TYPE logonType = TASK_LOGON_INTERACTIVE_TOKEN;

  // The outparam is not needed, but not documented as optional.
  RefPtr<IRegisteredTask> unusedTaskOutput = nullptr;
  HRESULT hr = folder.unwrap()->RegisterTask(
      bstrTaskName.get(), bstrXml.get(), flags, VARIANT{} /* userId */,
      VARIANT{} /* password */, logonType, VARIANT{} /* sddl */,
      getter_AddRefs(unusedTaskOutput));

  if (FAILED(hr)) {
    return ToAlreadyExistsOrFailure(hr);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::ValidateTaskDefinition(
    const char16_t* aDefinitionXML, int32_t* aResult) {
  if (!aDefinitionXML) {
    return NS_ERROR_NULL_POINTER;
  }

  auto folder = GetTaskFolder(reinterpret_cast<const char16_t*>(L"\\"));
  if (!folder.isOk()) {
    return NS_ERROR_FAILURE;
  }

  BStrPtr bstrXml = BStrPtr(
      ::SysAllocString(reinterpret_cast<const OLECHAR*>(aDefinitionXML)));
  LONG flags = TASK_VALIDATE_ONLY;
  TASK_LOGON_TYPE logonType = TASK_LOGON_INTERACTIVE_TOKEN;

  // The outparam is not needed, but not documented as optional.
  RefPtr<IRegisteredTask> unusedTaskOutput = nullptr;
  HRESULT hr = folder.unwrap()->RegisterTask(
      nullptr /* path */, bstrXml.get(), flags, VARIANT{} /* userId */,
      VARIANT{} /* password */, logonType, VARIANT{} /* sddl */,
      getter_AddRefs(unusedTaskOutput));

  if (aResult) {
    *aResult = hr;
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::DeleteTask(const char16_t* aFolderName,
                                      const char16_t* aTaskName) {
  if (!aFolderName || !aTaskName) {
    return NS_ERROR_NULL_POINTER;
  }

  auto folder = GetTaskFolder(aFolderName);
  if (!folder.isOk()) {
    return ToNotFoundOrFailure(folder.unwrapErr());
  }

  BStrPtr bstrTaskName =
      BStrPtr(::SysAllocString(reinterpret_cast<const OLECHAR*>(aTaskName)));

  HRESULT hr = folder.unwrap()->DeleteTask(bstrTaskName.get(), 0 /* flags */);
  if (FAILED(hr)) {
    return ToNotFoundOrFailure(hr);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::GetFolderTasks(const char16_t* aFolderName,
                                          nsTArray<nsString>& aResult) {
  if (!aFolderName) {
    return NS_ERROR_NULL_POINTER;
  }

  auto folder = GetTaskFolder(aFolderName);
  if (!folder.isOk()) {
    return ToNotFoundOrFailure(folder.unwrapErr());
  }

  RefPtr<IRegisteredTaskCollection> taskCollection = nullptr;
  if (FAILED(folder.unwrap()->GetTasks(TASK_ENUM_HIDDEN,
                                       getter_AddRefs(taskCollection)))) {
    return NS_ERROR_FAILURE;
  }

  LONG taskCount = 0;
  if (FAILED(taskCollection->get_Count(&taskCount))) {
    return NS_ERROR_FAILURE;
  }

  aResult.Clear();

  for (LONG i = 0; i < taskCount; ++i) {
    RefPtr<IRegisteredTask> task = nullptr;

    // nb: Collections are indexed from 1.
    if (FAILED(taskCollection->get_Item(_variant_t(i + 1),
                                        getter_AddRefs(task)))) {
      return NS_ERROR_FAILURE;
    }

    BStrPtr bstrTaskName;
    {
      BSTR tempTaskName = nullptr;
      if (FAILED(task->get_Name(&tempTaskName))) {
        return NS_ERROR_FAILURE;
      }
      bstrTaskName = BStrPtr(tempTaskName);
    }

    aResult.AppendElement(nsString(bstrTaskName.get()));
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::CreateFolder(const char16_t* aParentFolderName,
                                        const char16_t* aSubFolderName) {
  if (!aParentFolderName || !aSubFolderName) {
    return NS_ERROR_NULL_POINTER;
  }

  auto parentFolder = GetTaskFolder(aParentFolderName);
  if (!parentFolder.isOk()) {
    return ToNotFoundOrFailure(parentFolder.unwrapErr());
  }

  BStrPtr bstrSubFolderName = BStrPtr(
      ::SysAllocString(reinterpret_cast<const OLECHAR*>(aSubFolderName)));

  HRESULT hr = parentFolder.unwrap()->CreateFolder(bstrSubFolderName.get(),
                                                   VARIANT{},  // sddl
                                                   nullptr);   // ppFolder

  if (FAILED(hr)) {
    return ToAlreadyExistsOrFailure(hr);
  }

  return NS_OK;
}

NS_IMETHODIMP
nsWinTaskSchedulerService::DeleteFolder(const char16_t* aParentFolderName,
                                        const char16_t* aSubFolderName) {
  if (!aParentFolderName || !aSubFolderName) {
    return NS_ERROR_NULL_POINTER;
  }

  auto parentFolder = GetTaskFolder(aParentFolderName);
  if (!parentFolder.isOk()) {
    return ToNotFoundOrFailure(parentFolder.unwrapErr());
  }

  BStrPtr bstrSubFolderName = BStrPtr(
      ::SysAllocString(reinterpret_cast<const OLECHAR*>(aSubFolderName)));

  HRESULT hr = parentFolder.unwrap()->DeleteFolder(bstrSubFolderName.get(),
                                                   0 /* flags */);

  if (FAILED(hr)) {
    if (hr == HRESULT_FROM_WIN32(ERROR_DIR_NOT_EMPTY)) {
      return NS_ERROR_FILE_DIR_NOT_EMPTY;
    } else {
      return ToNotFoundOrFailure(hr);
    }
  }

  return NS_OK;
}