ntdll: Fix NtAccessCheck for NULL, but present SACLs and DACLs.
[wine] / dlls / ntdll / env.c
1 /*
2  * Ntdll environment functions
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  * Copyright 2003       Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21 #include "config.h"
22
23 #include <assert.h>
24 #include <stdarg.h>
25
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "windef.h"
29 #include "winternl.h"
30 #include "wine/unicode.h"
31 #include "wine/debug.h"
32 #include "thread.h"
33 #include "ntdll_misc.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(environ);
36
37 /******************************************************************************
38  *  RtlCreateEnvironment                [NTDLL.@]
39  */
40 NTSTATUS WINAPI RtlCreateEnvironment(BOOLEAN inherit, PWSTR* env)
41 {
42     NTSTATUS    nts;
43
44     TRACE("(%u,%p)!\n", inherit, env);
45
46     if (inherit)
47     {
48         MEMORY_BASIC_INFORMATION        mbi;
49
50         RtlAcquirePebLock();
51
52         nts = NtQueryVirtualMemory(NtCurrentProcess(),
53                                    NtCurrentTeb()->Peb->ProcessParameters->Environment,
54                                    0, &mbi, sizeof(mbi), NULL);
55         if (nts == STATUS_SUCCESS)
56         {
57             *env = NULL;
58             nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)env, 0, &mbi.RegionSize, 
59                                           MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
60             if (nts == STATUS_SUCCESS)
61                 memcpy(*env, NtCurrentTeb()->Peb->ProcessParameters->Environment, mbi.RegionSize);
62             else *env = NULL;
63         }
64         RtlReleasePebLock();
65     }
66     else 
67     {
68         SIZE_T      size = 1;
69         PVOID       addr = NULL;
70         nts = NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
71                                       MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
72         if (nts == STATUS_SUCCESS) *env = addr;
73     }
74
75     return nts;
76 }
77
78 /******************************************************************************
79  *  RtlDestroyEnvironment               [NTDLL.@]
80  */
81 NTSTATUS WINAPI RtlDestroyEnvironment(PWSTR env) 
82 {
83     SIZE_T size = 0;
84
85     TRACE("(%p)!\n", env);
86
87     return NtFreeVirtualMemory(NtCurrentProcess(), (void**)&env, &size, MEM_RELEASE);
88 }
89
90 static LPCWSTR ENV_FindVariable(PCWSTR var, PCWSTR name, unsigned namelen)
91 {
92     for (; *var; var += strlenW(var) + 1)
93     {
94         /* match var names, but avoid setting a var with a name including a '='
95          * (a starting '=' is valid though)
96          */
97         if (strncmpiW(var, name, namelen) == 0 && var[namelen] == '=' &&
98             strchrW(var + 1, '=') == var + namelen) 
99         {
100             return var + namelen + 1;
101         }
102     }
103     return NULL;
104 }
105
106 /******************************************************************
107  *              RtlQueryEnvironmentVariable_U   [NTDLL.@]
108  *
109  * NOTES: when the buffer is too small, the string is not written, but if the
110  *      terminating null char is the only char that cannot be written, then
111  *      all chars (except the null) are written and success is returned
112  *      (behavior of Win2k at least)
113  */
114 NTSTATUS WINAPI RtlQueryEnvironmentVariable_U(PWSTR env,
115                                               PUNICODE_STRING name,
116                                               PUNICODE_STRING value)
117 {
118     NTSTATUS    nts = STATUS_VARIABLE_NOT_FOUND;
119     PCWSTR      var;
120     unsigned    namelen;
121
122     TRACE("%p %s %p\n", env, debugstr_us(name), value);
123
124     value->Length = 0;
125     namelen = name->Length / sizeof(WCHAR);
126     if (!namelen) return nts;
127
128     if (!env)
129     {
130         RtlAcquirePebLock();
131         var = NtCurrentTeb()->Peb->ProcessParameters->Environment;
132     }
133     else var = env;
134
135     var = ENV_FindVariable(var, name->Buffer, namelen);
136     if (var != NULL)
137     {
138         value->Length = strlenW(var) * sizeof(WCHAR);
139
140         if (value->Length <= value->MaximumLength)
141         {
142             memmove(value->Buffer, var, min(value->Length + sizeof(WCHAR), value->MaximumLength));
143             nts = STATUS_SUCCESS;
144         }
145         else nts = STATUS_BUFFER_TOO_SMALL;
146     }
147
148     if (!env) RtlReleasePebLock();
149
150     return nts;
151 }
152
153 /******************************************************************
154  *              RtlSetCurrentEnvironment        [NTDLL.@]
155  *
156  */
157 void WINAPI RtlSetCurrentEnvironment(PWSTR new_env, PWSTR* old_env)
158 {
159     TRACE("(%p %p)\n", new_env, old_env);
160
161     RtlAcquirePebLock();
162
163     if (old_env) *old_env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
164     NtCurrentTeb()->Peb->ProcessParameters->Environment = new_env;
165
166     RtlReleasePebLock();
167 }
168
169
170 /******************************************************************************
171  *  RtlSetEnvironmentVariable           [NTDLL.@]
172  */
173 NTSTATUS WINAPI RtlSetEnvironmentVariable(PWSTR* penv, PUNICODE_STRING name, 
174                                           PUNICODE_STRING value)
175 {
176     INT         len, old_size;
177     LPWSTR      p, env;
178     NTSTATUS    nts = STATUS_VARIABLE_NOT_FOUND;
179     MEMORY_BASIC_INFORMATION mbi;
180
181     TRACE("(%p, %s, %s)\n", penv, debugstr_us(name), debugstr_us(value));
182
183     if (!name || !name->Buffer || !name->Length)
184         return STATUS_INVALID_PARAMETER_1;
185
186     len = name->Length / sizeof(WCHAR);
187
188     /* variable names can't contain a '=' except as a first character */
189     for (p = name->Buffer + 1; p < name->Buffer + len; p++)
190         if (*p == '=') return STATUS_INVALID_PARAMETER;
191
192     if (!penv)
193     {
194         RtlAcquirePebLock();
195         env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
196     } else env = *penv;
197
198     /* compute current size of environment */
199     for (p = env; *p; p += strlenW(p) + 1);
200     old_size = p + 1 - env;
201
202     /* Find a place to insert the string */
203     for (p = env; *p; p += strlenW(p) + 1)
204     {
205         if (!strncmpiW(name->Buffer, p, len) && (p[len] == '=')) break;
206     }
207     if (!value && !*p) goto done;  /* Value to remove doesn't exist */
208
209     /* Realloc the buffer */
210     len = value ? len + value->Length / sizeof(WCHAR) + 2 : 0;
211     if (*p) len -= strlenW(p) + 1;  /* The name already exists */
212
213     if (len < 0)
214     {
215         LPWSTR next = p + strlenW(p) + 1;  /* We know there is a next one */
216         memmove(next + len, next, (old_size - (next - env)) * sizeof(WCHAR));
217     }
218
219     nts = NtQueryVirtualMemory(NtCurrentProcess(), env, 0,
220                                &mbi, sizeof(mbi), NULL);
221     if (nts != STATUS_SUCCESS) goto done;
222
223     if ((old_size + len) * sizeof(WCHAR) > mbi.RegionSize)
224     {
225         LPWSTR  new_env;
226         SIZE_T  new_size = (old_size + len) * sizeof(WCHAR);
227
228         new_env = NULL;
229         nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)&new_env, 0,
230                                       &new_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
231         if (nts != STATUS_SUCCESS) goto done;
232
233         memmove(new_env, env, (p - env) * sizeof(WCHAR));
234         assert(len > 0);
235         memmove(new_env + (p - env) + len, p, (old_size - (p - env)) * sizeof(WCHAR));
236         p = new_env + (p - env);
237
238         RtlDestroyEnvironment(env);
239         if (!penv) NtCurrentTeb()->Peb->ProcessParameters->Environment = new_env;
240         else *penv = new_env;
241         env = new_env;
242     }
243     else
244     {
245         if (len > 0) memmove(p + len, p, (old_size - (p - env)) * sizeof(WCHAR));
246     }
247
248     /* Set the new string */
249     if (value)
250     {
251         memcpy( p, name->Buffer, name->Length );
252         p += name->Length / sizeof(WCHAR);
253         *p++ = '=';
254         memcpy( p, value->Buffer, value->Length );
255         p[value->Length / sizeof(WCHAR)] = 0;
256     }
257 done:
258     if (!penv) RtlReleasePebLock();
259
260     return nts;
261 }
262
263 /******************************************************************
264  *              RtlExpandEnvironmentStrings_U (NTDLL.@)
265  *
266  */
267 NTSTATUS WINAPI RtlExpandEnvironmentStrings_U(PCWSTR renv, const UNICODE_STRING* us_src,
268                                               PUNICODE_STRING us_dst, PULONG plen)
269 {
270     DWORD src_len, len, count, total_size = 1;  /* 1 for terminating '\0' */
271     LPCWSTR     env, src, p, var;
272     LPWSTR      dst;
273
274     src = us_src->Buffer;
275     src_len = us_src->Length / sizeof(WCHAR);
276     count = us_dst->MaximumLength / sizeof(WCHAR);
277     dst = count ? us_dst->Buffer : NULL;
278
279     if (!renv)
280     {
281         RtlAcquirePebLock();
282         env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
283     }
284     else env = renv;
285
286     while (src_len)
287     {
288         if (*src != '%')
289         {
290             if ((p = memchrW( src, '%', src_len ))) len = p - src;
291             else len = src_len;
292             var = src;
293             src += len;
294             src_len -= len;
295         }
296         else  /* we are at the start of a variable */
297         {
298             if ((p = memchrW( src + 1, '%', src_len - 1 )))
299             {
300                 len = p - src - 1;  /* Length of the variable name */
301                 if ((var = ENV_FindVariable( env, src + 1, len )))
302                 {
303                     src += len + 2;  /* Skip the variable name */
304                     src_len -= len + 2;
305                     len = strlenW(var);
306                 }
307                 else
308                 {
309                     var = src;  /* Copy original name instead */
310                     len += 2;
311                     src += len;
312                     src_len -= len;
313                 }
314             }
315             else  /* unfinished variable name, ignore it */
316             {
317                 var = src;
318                 len = src_len;  /* Copy whole string */
319                 src += len;
320                 src_len = 0;
321             }
322         }
323         total_size += len;
324         if (dst)
325         {
326             if (count < len) len = count;
327             memcpy(dst, var, len * sizeof(WCHAR));
328             count -= len;
329             dst += len;
330         }
331     }
332
333     if (!renv) RtlReleasePebLock();
334
335     /* Null-terminate the string */
336     if (dst && count) *dst = '\0';
337
338     us_dst->Length = (dst) ? (dst - us_dst->Buffer) * sizeof(WCHAR) : 0;
339     if (plen) *plen = total_size * sizeof(WCHAR);
340
341     return (count) ? STATUS_SUCCESS : STATUS_BUFFER_TOO_SMALL;
342 }
343
344
345 static inline void normalize( void *base, WCHAR **ptr )
346 {
347     if (*ptr) *ptr = (WCHAR *)((char *)base + (UINT_PTR)*ptr);
348 }
349
350 /******************************************************************************
351  *  RtlNormalizeProcessParams  [NTDLL.@]
352  */
353 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
354 {
355     if (params && !(params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
356     {
357         normalize( params, &params->CurrentDirectory.DosPath.Buffer );
358         normalize( params, &params->DllPath.Buffer );
359         normalize( params, &params->ImagePathName.Buffer );
360         normalize( params, &params->CommandLine.Buffer );
361         normalize( params, &params->WindowTitle.Buffer );
362         normalize( params, &params->Desktop.Buffer );
363         normalize( params, &params->ShellInfo.Buffer );
364         normalize( params, &params->RuntimeInfo.Buffer );
365         params->Flags |= PROCESS_PARAMS_FLAG_NORMALIZED;
366     }
367     return params;
368 }
369
370
371 static inline void denormalize( const void *base, WCHAR **ptr )
372 {
373     if (*ptr) *ptr = (WCHAR *)(UINT_PTR)((char *)*ptr - (const char *)base);
374 }
375
376 /******************************************************************************
377  *  RtlDeNormalizeProcessParams  [NTDLL.@]
378  */
379 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlDeNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
380 {
381     if (params && (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
382     {
383         denormalize( params, &params->CurrentDirectory.DosPath.Buffer );
384         denormalize( params, &params->DllPath.Buffer );
385         denormalize( params, &params->ImagePathName.Buffer );
386         denormalize( params, &params->CommandLine.Buffer );
387         denormalize( params, &params->WindowTitle.Buffer );
388         denormalize( params, &params->Desktop.Buffer );
389         denormalize( params, &params->ShellInfo.Buffer );
390         denormalize( params, &params->RuntimeInfo.Buffer );
391         params->Flags &= ~PROCESS_PARAMS_FLAG_NORMALIZED;
392     }
393     return params;
394 }
395
396
397 /* append a unicode string to the process params data; helper for RtlCreateProcessParameters */
398 static void append_unicode_string( void **data, const UNICODE_STRING *src,
399                                    UNICODE_STRING *dst )
400 {
401     dst->Length = src->Length;
402     dst->MaximumLength = src->MaximumLength;
403     dst->Buffer = *data;
404     memcpy( dst->Buffer, src->Buffer, dst->MaximumLength );
405     *data = (char *)dst->Buffer + dst->MaximumLength;
406 }
407
408
409 /******************************************************************************
410  *  RtlCreateProcessParameters  [NTDLL.@]
411  */
412 NTSTATUS WINAPI RtlCreateProcessParameters( RTL_USER_PROCESS_PARAMETERS **result,
413                                             const UNICODE_STRING *ImagePathName,
414                                             const UNICODE_STRING *DllPath,
415                                             const UNICODE_STRING *CurrentDirectoryName,
416                                             const UNICODE_STRING *CommandLine,
417                                             PWSTR Environment,
418                                             const UNICODE_STRING *WindowTitle,
419                                             const UNICODE_STRING *Desktop,
420                                             const UNICODE_STRING *ShellInfo,
421                                             const UNICODE_STRING *RuntimeInfo )
422 {
423     static WCHAR empty[] = {0};
424     static const UNICODE_STRING empty_str = { 0, sizeof(empty), empty };
425     static const UNICODE_STRING null_str = { 0, 0, NULL };
426
427     const RTL_USER_PROCESS_PARAMETERS *cur_params;
428     SIZE_T size, total_size;
429     void *ptr;
430     NTSTATUS status;
431
432     RtlAcquirePebLock();
433     cur_params = NtCurrentTeb()->Peb->ProcessParameters;
434     if (!DllPath) DllPath = &cur_params->DllPath;
435     if (!CurrentDirectoryName)
436     {
437         if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
438             CurrentDirectoryName = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
439         else
440             CurrentDirectoryName = &cur_params->CurrentDirectory.DosPath;
441     }
442     if (!CommandLine) CommandLine = ImagePathName;
443     if (!Environment) Environment = cur_params->Environment;
444     if (!WindowTitle) WindowTitle = &empty_str;
445     if (!Desktop) Desktop = &empty_str;
446     if (!ShellInfo) ShellInfo = &empty_str;
447     if (!RuntimeInfo) RuntimeInfo = &null_str;
448
449     size = (sizeof(RTL_USER_PROCESS_PARAMETERS)
450             + ImagePathName->MaximumLength
451             + DllPath->MaximumLength
452             + CurrentDirectoryName->MaximumLength
453             + CommandLine->MaximumLength
454             + WindowTitle->MaximumLength
455             + Desktop->MaximumLength
456             + ShellInfo->MaximumLength
457             + RuntimeInfo->MaximumLength);
458
459     total_size = size;
460     ptr = NULL;
461     if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &total_size,
462                                            MEM_COMMIT, PAGE_READWRITE )) == STATUS_SUCCESS)
463     {
464         RTL_USER_PROCESS_PARAMETERS *params = ptr;
465         params->AllocationSize = total_size;
466         params->Size           = size;
467         params->Flags          = PROCESS_PARAMS_FLAG_NORMALIZED;
468         params->ConsoleFlags   = cur_params->ConsoleFlags;
469         params->Environment    = Environment;
470         /* all other fields are zero */
471
472         ptr = params + 1;
473         append_unicode_string( &ptr, CurrentDirectoryName, &params->CurrentDirectory.DosPath );
474         append_unicode_string( &ptr, DllPath, &params->DllPath );
475         append_unicode_string( &ptr, ImagePathName, &params->ImagePathName );
476         append_unicode_string( &ptr, CommandLine, &params->CommandLine );
477         append_unicode_string( &ptr, WindowTitle, &params->WindowTitle );
478         append_unicode_string( &ptr, Desktop, &params->Desktop );
479         append_unicode_string( &ptr, ShellInfo, &params->ShellInfo );
480         append_unicode_string( &ptr, RuntimeInfo, &params->RuntimeInfo );
481         *result = RtlDeNormalizeProcessParams( params );
482     }
483     RtlReleasePebLock();
484     return status;
485 }
486
487
488 /******************************************************************************
489  *  RtlDestroyProcessParameters  [NTDLL.@]
490  */
491 void WINAPI RtlDestroyProcessParameters( RTL_USER_PROCESS_PARAMETERS *params )
492 {
493     void *ptr = params;
494     SIZE_T size = 0;
495     NtFreeVirtualMemory( NtCurrentProcess(), &ptr, &size, MEM_RELEASE );
496 }