]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winmisc.c
Make get_user_sid() return the cached copy if one already exists.
[PuTTY.git] / windows / winmisc.c
1 /*
2  * winmisc.c: miscellaneous Windows-specific things
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "putty.h"
8 #define SECURITY_WIN32
9 #include <security.h>
10
11 OSVERSIONINFO osVersion;
12
13 char *platform_get_x_display(void) {
14     /* We may as well check for DISPLAY in case it's useful. */
15     return dupstr(getenv("DISPLAY"));
16 }
17
18 Filename *filename_from_str(const char *str)
19 {
20     Filename *ret = snew(Filename);
21     ret->path = dupstr(str);
22     return ret;
23 }
24
25 Filename *filename_copy(const Filename *fn)
26 {
27     return filename_from_str(fn->path);
28 }
29
30 const char *filename_to_str(const Filename *fn)
31 {
32     return fn->path;
33 }
34
35 int filename_equal(const Filename *f1, const Filename *f2)
36 {
37     return !strcmp(f1->path, f2->path);
38 }
39
40 int filename_is_null(const Filename *fn)
41 {
42     return !*fn->path;
43 }
44
45 void filename_free(Filename *fn)
46 {
47     sfree(fn->path);
48     sfree(fn);
49 }
50
51 int filename_serialise(const Filename *f, void *vdata)
52 {
53     char *data = (char *)vdata;
54     int len = strlen(f->path) + 1;     /* include trailing NUL */
55     if (data) {
56         strcpy(data, f->path);
57     }
58     return len;
59 }
60 Filename *filename_deserialise(void *vdata, int maxsize, int *used)
61 {
62     char *data = (char *)vdata;
63     char *end;
64     end = memchr(data, '\0', maxsize);
65     if (!end)
66         return NULL;
67     end++;
68     *used = end - data;
69     return filename_from_str(data);
70 }
71
72 char filename_char_sanitise(char c)
73 {
74     if (strchr("<>:\"/\\|?*", c))
75         return '.';
76     return c;
77 }
78
79 #ifndef NO_SECUREZEROMEMORY
80 /*
81  * Windows implementation of smemclr (see misc.c) using SecureZeroMemory.
82  */
83 void smemclr(void *b, size_t n) {
84     if (b && n > 0)
85         SecureZeroMemory(b, n);
86 }
87 #endif
88
89 char *get_username(void)
90 {
91     DWORD namelen;
92     char *user;
93     int got_username = FALSE;
94     DECL_WINDOWS_FUNCTION(static, BOOLEAN, GetUserNameExA,
95                           (EXTENDED_NAME_FORMAT, LPSTR, PULONG));
96
97     {
98         static int tried_usernameex = FALSE;
99         if (!tried_usernameex) {
100             /* Not available on Win9x, so load dynamically */
101             HMODULE secur32 = load_system32_dll("secur32.dll");
102             GET_WINDOWS_FUNCTION(secur32, GetUserNameExA);
103             tried_usernameex = TRUE;
104         }
105     }
106
107     if (p_GetUserNameExA) {
108         /*
109          * If available, use the principal -- this avoids the problem
110          * that the local username is case-insensitive but Kerberos
111          * usernames are case-sensitive.
112          */
113
114         /* Get the length */
115         namelen = 0;
116         (void) p_GetUserNameExA(NameUserPrincipal, NULL, &namelen);
117
118         user = snewn(namelen, char);
119         got_username = p_GetUserNameExA(NameUserPrincipal, user, &namelen);
120         if (got_username) {
121             char *p = strchr(user, '@');
122             if (p) *p = 0;
123         } else {
124             sfree(user);
125         }
126     }
127
128     if (!got_username) {
129         /* Fall back to local user name */
130         namelen = 0;
131         if (GetUserName(NULL, &namelen) == FALSE) {
132             /*
133              * Apparently this doesn't work at least on Windows XP SP2.
134              * Thus assume a maximum of 256. It will fail again if it
135              * doesn't fit.
136              */
137             namelen = 256;
138         }
139
140         user = snewn(namelen, char);
141         got_username = GetUserName(user, &namelen);
142         if (!got_username) {
143             sfree(user);
144         }
145     }
146
147     return got_username ? user : NULL;
148 }
149
150 BOOL init_winver(void)
151 {
152     ZeroMemory(&osVersion, sizeof(osVersion));
153     osVersion.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
154     return GetVersionEx ( (OSVERSIONINFO *) &osVersion);
155 }
156
157 HMODULE load_system32_dll(const char *libname)
158 {
159     /*
160      * Wrapper function to load a DLL out of c:\windows\system32
161      * without going through the full DLL search path. (Hence no
162      * attack is possible by placing a substitute DLL earlier on that
163      * path.)
164      */
165     static char *sysdir = NULL;
166     char *fullpath;
167     HMODULE ret;
168
169     if (!sysdir) {
170         int size = 0, len;
171         do {
172             size = 3*size/2 + 512;
173             sysdir = sresize(sysdir, size, char);
174             len = GetSystemDirectory(sysdir, size);
175         } while (len >= size);
176     }
177
178     fullpath = dupcat(sysdir, "\\", libname, NULL);
179     ret = LoadLibrary(fullpath);
180     sfree(fullpath);
181     return ret;
182 }
183
184 /*
185  * A tree234 containing mappings from system error codes to strings.
186  */
187
188 struct errstring {
189     int error;
190     char *text;
191 };
192
193 static int errstring_find(void *av, void *bv)
194 {
195     int *a = (int *)av;
196     struct errstring *b = (struct errstring *)bv;
197     if (*a < b->error)
198         return -1;
199     if (*a > b->error)
200         return +1;
201     return 0;
202 }
203 static int errstring_compare(void *av, void *bv)
204 {
205     struct errstring *a = (struct errstring *)av;
206     return errstring_find(&a->error, bv);
207 }
208
209 static tree234 *errstrings = NULL;
210
211 const char *win_strerror(int error)
212 {
213     struct errstring *es;
214
215     if (!errstrings)
216         errstrings = newtree234(errstring_compare);
217
218     es = find234(errstrings, &error, errstring_find);
219
220     if (!es) {
221         char msgtext[65536]; /* maximum size for FormatMessage is 64K */
222
223         es = snew(struct errstring);
224         es->error = error;
225         if (!FormatMessage((FORMAT_MESSAGE_FROM_SYSTEM |
226                             FORMAT_MESSAGE_IGNORE_INSERTS), NULL, error,
227                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
228                            msgtext, lenof(msgtext)-1, NULL)) {
229             sprintf(msgtext,
230                     "(unable to format: FormatMessage returned %d)",
231                     GetLastError());
232         } else {
233             int len = strlen(msgtext);
234             if (len > 0 && msgtext[len-1] == '\n')
235                 msgtext[len-1] = '\0';
236         }
237         es->text = dupprintf("Error %d: %s", error, msgtext);
238         add234(errstrings, es);
239     }
240
241     return es->text;
242 }
243
244 #ifdef DEBUG
245 static FILE *debug_fp = NULL;
246 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
247 static int debug_got_console = 0;
248
249 void dputs(char *buf)
250 {
251     DWORD dw;
252
253     if (!debug_got_console) {
254         if (AllocConsole()) {
255             debug_got_console = 1;
256             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
257         }
258     }
259     if (!debug_fp) {
260         debug_fp = fopen("debug.log", "w");
261     }
262
263     if (debug_hdl != INVALID_HANDLE_VALUE) {
264         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
265     }
266     fputs(buf, debug_fp);
267     fflush(debug_fp);
268 }
269 #endif
270
271 #ifdef MINEFIELD
272 /*
273  * Minefield - a Windows equivalent for Electric Fence
274  */
275
276 #define PAGESIZE 4096
277
278 /*
279  * Design:
280  * 
281  * We start by reserving as much virtual address space as Windows
282  * will sensibly (or not sensibly) let us have. We flag it all as
283  * invalid memory.
284  * 
285  * Any allocation attempt is satisfied by committing one or more
286  * pages, with an uncommitted page on either side. The returned
287  * memory region is jammed up against the _end_ of the pages.
288  * 
289  * Freeing anything causes instantaneous decommitment of the pages
290  * involved, so stale pointers are caught as soon as possible.
291  */
292
293 static int minefield_initialised = 0;
294 static void *minefield_region = NULL;
295 static long minefield_size = 0;
296 static long minefield_npages = 0;
297 static long minefield_curpos = 0;
298 static unsigned short *minefield_admin = NULL;
299 static void *minefield_pages = NULL;
300
301 static void minefield_admin_hide(int hide)
302 {
303     int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
304     VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
305 }
306
307 static void minefield_init(void)
308 {
309     int size;
310     int admin_size;
311     int i;
312
313     for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
314         minefield_region = VirtualAlloc(NULL, size,
315                                         MEM_RESERVE, PAGE_NOACCESS);
316         if (minefield_region)
317             break;
318     }
319     minefield_size = size;
320
321     /*
322      * Firstly, allocate a section of that to be the admin block.
323      * We'll need a two-byte field for each page.
324      */
325     minefield_admin = minefield_region;
326     minefield_npages = minefield_size / PAGESIZE;
327     admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
328     minefield_npages = (minefield_size - admin_size) / PAGESIZE;
329     minefield_pages = (char *) minefield_region + admin_size;
330
331     /*
332      * Commit the admin region.
333      */
334     VirtualAlloc(minefield_admin, minefield_npages * 2,
335                  MEM_COMMIT, PAGE_READWRITE);
336
337     /*
338      * Mark all pages as unused (0xFFFF).
339      */
340     for (i = 0; i < minefield_npages; i++)
341         minefield_admin[i] = 0xFFFF;
342
343     /*
344      * Hide the admin region.
345      */
346     minefield_admin_hide(1);
347
348     minefield_initialised = 1;
349 }
350
351 static void minefield_bomb(void)
352 {
353     div(1, *(int *) minefield_pages);
354 }
355
356 static void *minefield_alloc(int size)
357 {
358     int npages;
359     int pos, lim, region_end, region_start;
360     int start;
361     int i;
362
363     npages = (size + PAGESIZE - 1) / PAGESIZE;
364
365     minefield_admin_hide(0);
366
367     /*
368      * Search from current position until we find a contiguous
369      * bunch of npages+2 unused pages.
370      */
371     pos = minefield_curpos;
372     lim = minefield_npages;
373     while (1) {
374         /* Skip over used pages. */
375         while (pos < lim && minefield_admin[pos] != 0xFFFF)
376             pos++;
377         /* Count unused pages. */
378         start = pos;
379         while (pos < lim && pos - start < npages + 2 &&
380                minefield_admin[pos] == 0xFFFF)
381             pos++;
382         if (pos - start == npages + 2)
383             break;
384         /* If we've reached the limit, reset the limit or stop. */
385         if (pos >= lim) {
386             if (lim == minefield_npages) {
387                 /* go round and start again at zero */
388                 lim = minefield_curpos;
389                 pos = 0;
390             } else {
391                 minefield_admin_hide(1);
392                 return NULL;
393             }
394         }
395     }
396
397     minefield_curpos = pos - 1;
398
399     /*
400      * We have npages+2 unused pages starting at start. We leave
401      * the first and last of these alone and use the rest.
402      */
403     region_end = (start + npages + 1) * PAGESIZE;
404     region_start = region_end - size;
405     /* FIXME: could align here if we wanted */
406
407     /*
408      * Update the admin region.
409      */
410     for (i = start + 2; i < start + npages + 1; i++)
411         minefield_admin[i] = 0xFFFE;   /* used but no region starts here */
412     minefield_admin[start + 1] = region_start % PAGESIZE;
413
414     minefield_admin_hide(1);
415
416     VirtualAlloc((char *) minefield_pages + region_start, size,
417                  MEM_COMMIT, PAGE_READWRITE);
418     return (char *) minefield_pages + region_start;
419 }
420
421 static void minefield_free(void *ptr)
422 {
423     int region_start, i, j;
424
425     minefield_admin_hide(0);
426
427     region_start = (char *) ptr - (char *) minefield_pages;
428     i = region_start / PAGESIZE;
429     if (i < 0 || i >= minefield_npages ||
430         minefield_admin[i] != region_start % PAGESIZE)
431         minefield_bomb();
432     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
433         minefield_admin[j] = 0xFFFF;
434     }
435
436     VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
437
438     minefield_admin_hide(1);
439 }
440
441 static int minefield_get_size(void *ptr)
442 {
443     int region_start, i, j;
444
445     minefield_admin_hide(0);
446
447     region_start = (char *) ptr - (char *) minefield_pages;
448     i = region_start / PAGESIZE;
449     if (i < 0 || i >= minefield_npages ||
450         minefield_admin[i] != region_start % PAGESIZE)
451         minefield_bomb();
452     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
453
454     minefield_admin_hide(1);
455
456     return j * PAGESIZE - region_start;
457 }
458
459 void *minefield_c_malloc(size_t size)
460 {
461     if (!minefield_initialised)
462         minefield_init();
463     return minefield_alloc(size);
464 }
465
466 void minefield_c_free(void *p)
467 {
468     if (!minefield_initialised)
469         minefield_init();
470     minefield_free(p);
471 }
472
473 /*
474  * realloc _always_ moves the chunk, for rapid detection of code
475  * that assumes it won't.
476  */
477 void *minefield_c_realloc(void *p, size_t size)
478 {
479     size_t oldsize;
480     void *q;
481     if (!minefield_initialised)
482         minefield_init();
483     q = minefield_alloc(size);
484     oldsize = minefield_get_size(p);
485     memcpy(q, p, (oldsize < size ? oldsize : size));
486     minefield_free(p);
487     return q;
488 }
489
490 #endif                          /* MINEFIELD */
491
492 FontSpec *fontspec_new(const char *name,
493                         int bold, int height, int charset)
494 {
495     FontSpec *f = snew(FontSpec);
496     f->name = dupstr(name);
497     f->isbold = bold;
498     f->height = height;
499     f->charset = charset;
500     return f;
501 }
502 FontSpec *fontspec_copy(const FontSpec *f)
503 {
504     return fontspec_new(f->name, f->isbold, f->height, f->charset);
505 }
506 void fontspec_free(FontSpec *f)
507 {
508     sfree(f->name);
509     sfree(f);
510 }
511 int fontspec_serialise(FontSpec *f, void *vdata)
512 {
513     char *data = (char *)vdata;
514     int len = strlen(f->name) + 1;     /* include trailing NUL */
515     if (data) {
516         strcpy(data, f->name);
517         PUT_32BIT_MSB_FIRST(data + len, f->isbold);
518         PUT_32BIT_MSB_FIRST(data + len + 4, f->height);
519         PUT_32BIT_MSB_FIRST(data + len + 8, f->charset);
520     }
521     return len + 12;                   /* also include three 4-byte ints */
522 }
523 FontSpec *fontspec_deserialise(void *vdata, int maxsize, int *used)
524 {
525     char *data = (char *)vdata;
526     char *end;
527     if (maxsize < 13)
528         return NULL;
529     end = memchr(data, '\0', maxsize-12);
530     if (!end)
531         return NULL;
532     end++;
533     *used = end - data + 12;
534     return fontspec_new(data,
535                         GET_32BIT_MSB_FIRST(end),
536                         GET_32BIT_MSB_FIRST(end + 4),
537                         GET_32BIT_MSB_FIRST(end + 8));
538 }