1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/win/shortcut.h"
6
7 #include <objbase.h>
8
9 #include <propkey.h>
10 #include <shlobj.h>
11 #include <wrl/client.h>
12
13 #include "base/files/block_tests_writing_to_special_dirs.h"
14 #include "base/files/file_util.h"
15 #include "base/logging.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/threading/scoped_blocking_call.h"
19 #include "base/win/scoped_propvariant.h"
20 #include "base/win/win_util.h"
21 #include "base/win/windows_version.h"
22
23 namespace base {
24 namespace win {
25
26 namespace {
27
28 using Microsoft::WRL::ComPtr;
29
30 // Initializes |i_shell_link| and |i_persist_file| (releasing them first if they
31 // are already initialized).
32 // If |shortcut| is not NULL, loads |shortcut| into |i_persist_file|.
33 // If any of the above steps fail, both |i_shell_link| and |i_persist_file| will
34 // be released.
InitializeShortcutInterfaces(const wchar_t * shortcut,ComPtr<IShellLink> * i_shell_link,ComPtr<IPersistFile> * i_persist_file)35 void InitializeShortcutInterfaces(const wchar_t* shortcut,
36 ComPtr<IShellLink>* i_shell_link,
37 ComPtr<IPersistFile>* i_persist_file) {
38 // Reset in the inverse order of acquisition.
39 i_persist_file->Reset();
40 i_shell_link->Reset();
41
42 ComPtr<IShellLink> shell_link;
43 if (FAILED(::CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
44 IID_PPV_ARGS(&shell_link)))) {
45 return;
46 }
47 ComPtr<IPersistFile> persist_file;
48 if (FAILED(shell_link.As(&persist_file)))
49 return;
50 if (shortcut && FAILED(persist_file->Load(shortcut, STGM_READWRITE)))
51 return;
52 i_shell_link->Swap(shell_link);
53 i_persist_file->Swap(persist_file);
54 }
55
56 } // namespace
57
58 ShortcutProperties::ShortcutProperties() = default;
59
60 ShortcutProperties::ShortcutProperties(const ShortcutProperties& other) =
61 default;
62
63 ShortcutProperties::~ShortcutProperties() = default;
64
set_description(const std::wstring & description_in)65 void ShortcutProperties::set_description(const std::wstring& description_in) {
66 // Size restriction as per MSDN at http://goo.gl/OdNQq.
67 DCHECK_LE(description_in.size(), static_cast<size_t>(INFOTIPSIZE));
68 description = description_in;
69 options |= PROPERTIES_DESCRIPTION;
70 }
71
CreateOrUpdateShortcutLink(const FilePath & shortcut_path,const ShortcutProperties & properties,ShortcutOperation operation)72 bool CreateOrUpdateShortcutLink(const FilePath& shortcut_path,
73 const ShortcutProperties& properties,
74 ShortcutOperation operation) {
75 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
76
77 if (!BlockTestsWritingToSpecialDirs::CanWriteToPath(shortcut_path)) {
78 return false;
79 }
80 // Make sure the parent directories exist when creating the shortcut.
81 if (operation == ShortcutOperation::kCreateAlways &&
82 !base::CreateDirectory(shortcut_path.DirName())) {
83 DLOG(ERROR) << "CreateDirectory " << shortcut_path.DirName() << " failed";
84 return false;
85 }
86 // A target is required unless |operation| is kUpdateExisting.
87 if (operation != ShortcutOperation::kUpdateExisting &&
88 !(properties.options & ShortcutProperties::PROPERTIES_TARGET)) {
89 NOTREACHED();
90 }
91
92 bool shortcut_existed = PathExists(shortcut_path);
93
94 // Interfaces to the old shortcut when replacing an existing shortcut.
95 ComPtr<IShellLink> old_i_shell_link;
96 ComPtr<IPersistFile> old_i_persist_file;
97
98 // Interfaces to the shortcut being created/updated.
99 ComPtr<IShellLink> i_shell_link;
100 ComPtr<IPersistFile> i_persist_file;
101 switch (operation) {
102 case ShortcutOperation::kCreateAlways:
103 InitializeShortcutInterfaces(nullptr, &i_shell_link, &i_persist_file);
104 break;
105 case ShortcutOperation::kUpdateExisting:
106 InitializeShortcutInterfaces(shortcut_path.value().c_str(), &i_shell_link,
107 &i_persist_file);
108 break;
109 case ShortcutOperation::kReplaceExisting:
110 InitializeShortcutInterfaces(shortcut_path.value().c_str(),
111 &old_i_shell_link, &old_i_persist_file);
112 // Confirm |shortcut_path| exists and is a shortcut by verifying
113 // |old_i_persist_file| was successfully initialized in the call above. If
114 // so, initialize the interfaces to begin writing a new shortcut (to
115 // overwrite the current one if successful).
116 if (old_i_persist_file.Get())
117 InitializeShortcutInterfaces(nullptr, &i_shell_link, &i_persist_file);
118 break;
119 default:
120 NOTREACHED();
121 }
122
123 // Return false immediately upon failure to initialize shortcut interfaces.
124 if (!i_persist_file.Get())
125 return false;
126
127 if ((properties.options & ShortcutProperties::PROPERTIES_TARGET) &&
128 FAILED(i_shell_link->SetPath(properties.target.value().c_str()))) {
129 return false;
130 }
131
132 if ((properties.options & ShortcutProperties::PROPERTIES_WORKING_DIR) &&
133 FAILED(i_shell_link->SetWorkingDirectory(
134 properties.working_dir.value().c_str()))) {
135 return false;
136 }
137
138 if (properties.options & ShortcutProperties::PROPERTIES_ARGUMENTS) {
139 if (FAILED(i_shell_link->SetArguments(properties.arguments.c_str())))
140 return false;
141 } else if (old_i_persist_file.Get()) {
142 wchar_t current_arguments[MAX_PATH] = {0};
143 if (SUCCEEDED(
144 old_i_shell_link->GetArguments(current_arguments, MAX_PATH))) {
145 i_shell_link->SetArguments(current_arguments);
146 }
147 }
148
149 if ((properties.options & ShortcutProperties::PROPERTIES_DESCRIPTION) &&
150 FAILED(i_shell_link->SetDescription(properties.description.c_str()))) {
151 return false;
152 }
153
154 if ((properties.options & ShortcutProperties::PROPERTIES_ICON) &&
155 FAILED(i_shell_link->SetIconLocation(properties.icon.value().c_str(),
156 properties.icon_index))) {
157 return false;
158 }
159
160 bool has_app_id =
161 (properties.options & ShortcutProperties::PROPERTIES_APP_ID) != 0;
162 bool has_dual_mode =
163 (properties.options & ShortcutProperties::PROPERTIES_DUAL_MODE) != 0;
164 bool has_toast_activator_clsid =
165 (properties.options &
166 ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID) != 0;
167 if (has_app_id || has_dual_mode || has_toast_activator_clsid) {
168 ComPtr<IPropertyStore> property_store;
169 if (FAILED(i_shell_link.As(&property_store)) || !property_store.Get())
170 return false;
171
172 if (has_app_id && !SetAppIdForPropertyStore(property_store.Get(),
173 properties.app_id.c_str())) {
174 return false;
175 }
176 if (has_dual_mode && !SetBooleanValueForPropertyStore(
177 property_store.Get(), PKEY_AppUserModel_IsDualMode,
178 properties.dual_mode)) {
179 return false;
180 }
181 if (has_toast_activator_clsid &&
182 !SetClsidForPropertyStore(property_store.Get(),
183 PKEY_AppUserModel_ToastActivatorCLSID,
184 properties.toast_activator_clsid)) {
185 return false;
186 }
187 }
188
189 // Release the interfaces to the old shortcut to make sure it doesn't prevent
190 // overwriting it if needed.
191 old_i_persist_file.Reset();
192 old_i_shell_link.Reset();
193
194 HRESULT result = i_persist_file->Save(shortcut_path.value().c_str(), TRUE);
195
196 // Release the interfaces in case the SHChangeNotify call below depends on
197 // the operations above being fully completed.
198 i_persist_file.Reset();
199 i_shell_link.Reset();
200
201 // If we successfully created/updated the icon, notify the shell that we have
202 // done so.
203 if (!SUCCEEDED(result))
204 return false;
205
206 SHChangeNotify(shortcut_existed ? SHCNE_UPDATEITEM : SHCNE_CREATE,
207 SHCNF_PATH | SHCNF_FLUSH, shortcut_path.value().c_str(),
208 nullptr);
209
210 return true;
211 }
212
ResolveShortcutProperties(const FilePath & shortcut_path,uint32_t options,ShortcutProperties * properties)213 bool ResolveShortcutProperties(const FilePath& shortcut_path,
214 uint32_t options,
215 ShortcutProperties* properties) {
216 DCHECK(options && properties);
217 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
218
219 if (options & ~ShortcutProperties::PROPERTIES_ALL)
220 NOTREACHED() << "Unhandled property is used.";
221
222 ComPtr<IShellLink> i_shell_link;
223
224 // Get pointer to the IShellLink interface.
225 if (FAILED(::CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER,
226 IID_PPV_ARGS(&i_shell_link)))) {
227 return false;
228 }
229
230 ComPtr<IPersistFile> persist;
231 // Query IShellLink for the IPersistFile interface.
232 if (FAILED(i_shell_link.As(&persist)))
233 return false;
234
235 // Load the shell link.
236 if (FAILED(persist->Load(shortcut_path.value().c_str(), STGM_READ)))
237 return false;
238
239 // Reset |properties|.
240 properties->options = 0;
241
242 wchar_t temp[MAX_PATH];
243 if (options & ShortcutProperties::PROPERTIES_TARGET) {
244 if (FAILED(
245 i_shell_link->GetPath(temp, MAX_PATH, nullptr, SLGP_UNCPRIORITY))) {
246 return false;
247 }
248 properties->set_target(FilePath(temp));
249 }
250
251 if (options & ShortcutProperties::PROPERTIES_WORKING_DIR) {
252 if (FAILED(i_shell_link->GetWorkingDirectory(temp, MAX_PATH)))
253 return false;
254 properties->set_working_dir(FilePath(temp));
255 }
256
257 if (options & ShortcutProperties::PROPERTIES_ARGUMENTS) {
258 if (FAILED(i_shell_link->GetArguments(temp, MAX_PATH)))
259 return false;
260 properties->set_arguments(temp);
261 }
262
263 if (options & ShortcutProperties::PROPERTIES_DESCRIPTION) {
264 // Note: description length constrained by MAX_PATH.
265 if (FAILED(i_shell_link->GetDescription(temp, MAX_PATH)))
266 return false;
267 properties->set_description(temp);
268 }
269
270 if (options & ShortcutProperties::PROPERTIES_ICON) {
271 int temp_index;
272 if (FAILED(i_shell_link->GetIconLocation(temp, MAX_PATH, &temp_index))) {
273 return false;
274 }
275 properties->set_icon(FilePath(temp), temp_index);
276 }
277
278 if (options & (ShortcutProperties::PROPERTIES_APP_ID |
279 ShortcutProperties::PROPERTIES_DUAL_MODE |
280 ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID)) {
281 ComPtr<IPropertyStore> property_store;
282 if (FAILED(i_shell_link.As(&property_store)))
283 return false;
284
285 if (options & ShortcutProperties::PROPERTIES_APP_ID) {
286 ScopedPropVariant pv_app_id;
287 if (property_store->GetValue(PKEY_AppUserModel_ID, pv_app_id.Receive()) !=
288 S_OK) {
289 return false;
290 }
291 switch (pv_app_id.get().vt) {
292 case VT_EMPTY: {
293 properties->set_app_id(std::wstring());
294 break;
295 }
296 case VT_LPWSTR: {
297 properties->set_app_id(pv_app_id.get().pwszVal);
298 break;
299 }
300 case VT_BSTR: {
301 BSTR bs = pv_app_id.get().bstrVal;
302 properties->set_app_id(std::wstring(bs, ::SysStringLen(bs)));
303 break;
304 }
305 default: {
306 NOTREACHED() << "Unexpected variant type: " << pv_app_id.get().vt;
307 }
308 }
309 }
310
311 if (options & ShortcutProperties::PROPERTIES_DUAL_MODE) {
312 ScopedPropVariant pv_dual_mode;
313 if (property_store->GetValue(PKEY_AppUserModel_IsDualMode,
314 pv_dual_mode.Receive()) != S_OK) {
315 return false;
316 }
317 switch (pv_dual_mode.get().vt) {
318 case VT_EMPTY:
319 properties->set_dual_mode(false);
320 break;
321 case VT_BOOL:
322 properties->set_dual_mode(pv_dual_mode.get().boolVal == VARIANT_TRUE);
323 break;
324 default:
325 NOTREACHED() << "Unexpected variant type: " << pv_dual_mode.get().vt;
326 }
327 }
328
329 if (options & ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID) {
330 ScopedPropVariant pv_toast_activator_clsid;
331 if (property_store->GetValue(PKEY_AppUserModel_ToastActivatorCLSID,
332 pv_toast_activator_clsid.Receive()) !=
333 S_OK) {
334 return false;
335 }
336 switch (pv_toast_activator_clsid.get().vt) {
337 case VT_EMPTY:
338 properties->set_toast_activator_clsid(CLSID_NULL);
339 break;
340 case VT_CLSID:
341 properties->set_toast_activator_clsid(
342 *(pv_toast_activator_clsid.get().puuid));
343 break;
344 default:
345 NOTREACHED() << "Unexpected variant type: "
346 << pv_toast_activator_clsid.get().vt;
347 }
348 }
349 }
350
351 return true;
352 }
353
ResolveShortcut(const FilePath & shortcut_path,FilePath * target_path,std::wstring * args)354 bool ResolveShortcut(const FilePath& shortcut_path,
355 FilePath* target_path,
356 std::wstring* args) {
357 uint32_t options = 0;
358 if (target_path)
359 options |= ShortcutProperties::PROPERTIES_TARGET;
360 if (args)
361 options |= ShortcutProperties::PROPERTIES_ARGUMENTS;
362 DCHECK(options);
363
364 ShortcutProperties properties;
365 if (!ResolveShortcutProperties(shortcut_path, options, &properties))
366 return false;
367
368 if (target_path)
369 *target_path = properties.target;
370 if (args)
371 *args = properties.arguments;
372 return true;
373 }
374
375 } // namespace win
376 } // namespace base
377