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