Removed some unnecessary inclusions of thread.h
[wine] / dlls / kernel / profile.c
1 /*
2  * Profile functions
3  *
4  * Copyright 1993 Miguel de Icaza
5  * Copyright 1996 Alexandre Julliard
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <string.h>
26 #include <stdarg.h>
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winnls.h"
31 #include "winerror.h"
32 #include "winreg.h"
33 #include "winternl.h"
34 #include "wine/winbase16.h"
35 #include "wine/unicode.h"
36 #include "wine/server.h"
37 #include "wine/library.h"
38 #include "wine/debug.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(profile);
41
42 static const char bom_utf8[] = {0xEF,0xBB,0xBF};
43
44 typedef enum
45 {
46     ENCODING_ANSI = 1,
47     ENCODING_UTF8,
48     ENCODING_UTF16LE,
49     ENCODING_UTF16BE
50 } ENCODING;
51
52 typedef struct tagPROFILEKEY
53 {
54     WCHAR                 *value;
55     struct tagPROFILEKEY  *next;
56     WCHAR                  name[1];
57 } PROFILEKEY;
58
59 typedef struct tagPROFILESECTION
60 {
61     struct tagPROFILEKEY       *key;
62     struct tagPROFILESECTION   *next;
63     WCHAR                       name[1];
64 } PROFILESECTION;
65
66
67 typedef struct
68 {
69     BOOL             changed;
70     PROFILESECTION  *section;
71     WCHAR           *filename;
72     FILETIME LastWriteTime;
73     ENCODING encoding;
74 } PROFILE;
75
76
77 #define N_CACHED_PROFILES 10
78
79 /* Cached profile files */
80 static PROFILE *MRUProfile[N_CACHED_PROFILES]={NULL};
81
82 #define CurProfile (MRUProfile[0])
83
84 /* Check for comments in profile */
85 #define IS_ENTRY_COMMENT(str)  ((str)[0] == ';')
86
87 static const WCHAR emptystringW[] = {0};
88 static const WCHAR wininiW[] = { 'w','i','n','.','i','n','i',0 };
89
90 static CRITICAL_SECTION PROFILE_CritSect;
91 static CRITICAL_SECTION_DEBUG critsect_debug =
92 {
93     0, 0, &PROFILE_CritSect,
94     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
95       0, 0, { 0, (DWORD)(__FILE__ ": PROFILE_CritSect") }
96 };
97 static CRITICAL_SECTION PROFILE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
98
99 static const char hex[16] = "0123456789ABCDEF";
100
101 /***********************************************************************
102  *           PROFILE_CopyEntry
103  *
104  * Copy the content of an entry into a buffer, removing quotes, and possibly
105  * translating environment variables.
106  */
107 static void PROFILE_CopyEntry( LPWSTR buffer, LPCWSTR value, int len,
108                                BOOL strip_quote )
109 {
110     WCHAR quote = '\0';
111
112     if(!buffer) return;
113
114     if (strip_quote && ((*value == '\'') || (*value == '\"')))
115     {
116         if (value[1] && (value[strlenW(value)-1] == *value)) quote = *value++;
117     }
118
119     lstrcpynW( buffer, value, len );
120     if (quote && (len >= strlenW(value))) buffer[strlenW(buffer)-1] = '\0';
121 }
122
123 /* byte-swaps shorts in-place in a buffer. len is in WCHARs */
124 static inline void PROFILE_ByteSwapShortBuffer(WCHAR * buffer, int len)
125 {
126     int i;
127     USHORT * shortbuffer = (USHORT *)buffer;
128     for (i = 0; i < len; i++)
129         shortbuffer[i] = RtlUshortByteSwap(shortbuffer[i]);
130 }
131
132 /* writes any necessary encoding marker to the file */
133 static inline void PROFILE_WriteMarker(HANDLE hFile, ENCODING encoding)
134 {
135     DWORD dwBytesWritten;
136     DWORD bom;
137     switch (encoding)
138     {
139     case ENCODING_ANSI:
140         break;
141     case ENCODING_UTF8:
142         WriteFile(hFile, bom_utf8, sizeof(bom_utf8), &dwBytesWritten, NULL);
143         break;
144     case ENCODING_UTF16LE:
145         bom = 0xFEFF;
146         WriteFile(hFile, &bom, sizeof(bom), &dwBytesWritten, NULL);
147         break;
148     case ENCODING_UTF16BE:
149         bom = 0xFFFE;
150         WriteFile(hFile, &bom, sizeof(bom), &dwBytesWritten, NULL);
151         break;
152     }
153 }
154
155 static void PROFILE_WriteLine( HANDLE hFile, WCHAR * szLine, int len, ENCODING encoding)
156 {
157     char * write_buffer;
158     int write_buffer_len;
159     DWORD dwBytesWritten;
160
161     TRACE("writing: %s\n", debugstr_wn(szLine, len));
162
163     switch (encoding)
164     {
165     case ENCODING_ANSI:
166         write_buffer_len = WideCharToMultiByte(CP_ACP, 0, szLine, len, NULL, 0, NULL, NULL);
167         write_buffer = HeapAlloc(GetProcessHeap(), 0, write_buffer_len);
168         if (!write_buffer) return;
169         len = WideCharToMultiByte(CP_ACP, 0, szLine, len, write_buffer, write_buffer_len, NULL, NULL);
170         WriteFile(hFile, write_buffer, len, &dwBytesWritten, NULL);
171         HeapFree(GetProcessHeap(), 0, write_buffer);
172         break;
173     case ENCODING_UTF8:
174         write_buffer_len = WideCharToMultiByte(CP_UTF8, 0, szLine, len, NULL, 0, NULL, NULL);
175         write_buffer = HeapAlloc(GetProcessHeap(), 0, write_buffer_len);
176         if (!write_buffer) return;
177         len = WideCharToMultiByte(CP_UTF8, 0, szLine, len, write_buffer, write_buffer_len, NULL, NULL);
178         WriteFile(hFile, write_buffer, len, &dwBytesWritten, NULL);
179         HeapFree(GetProcessHeap(), 0, write_buffer);
180         break;
181     case ENCODING_UTF16LE:
182         WriteFile(hFile, szLine, len * sizeof(WCHAR), &dwBytesWritten, NULL);
183         break;
184     case ENCODING_UTF16BE:
185         PROFILE_ByteSwapShortBuffer(szLine, len);
186         WriteFile(hFile, szLine, len * sizeof(WCHAR), &dwBytesWritten, NULL);
187         break;
188     default:
189         FIXME("encoding type %d not implemented\n", encoding);
190     }
191 }
192
193 /***********************************************************************
194  *           PROFILE_Save
195  *
196  * Save a profile tree to a file.
197  */
198 static void PROFILE_Save( HANDLE hFile, const PROFILESECTION *section, ENCODING encoding )
199 {
200     PROFILEKEY *key;
201     WCHAR *buffer, *p;
202
203     PROFILE_WriteMarker(hFile, encoding);
204
205     for ( ; section; section = section->next)
206     {
207         int len = 0;
208
209         if (section->name[0]) len += strlenW(section->name) + 6;
210
211         for (key = section->key; key; key = key->next)
212         {
213             len += strlenW(key->name) + 2;
214             if (key->value) len += strlenW(key->value) + 1;
215         }
216
217         buffer = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
218         if (!buffer) return;
219
220         p = buffer;
221         if (section->name[0])
222         {
223             *p++ = '\r';
224             *p++ = '\n';
225             *p++ = '[';
226             strcpyW( p, section->name );
227             p += strlenW(p);
228             *p++ = ']';
229             *p++ = '\r';
230             *p++ = '\n';
231         }
232         for (key = section->key; key; key = key->next)
233         {
234             strcpyW( p, key->name );
235             p += strlenW(p);
236             if (key->value)
237             {
238                 *p++ = '=';
239                 strcpyW( p, key->value );
240                 p += strlenW(p);
241             }
242             *p++ = '\r';
243             *p++ = '\n';
244         }
245         PROFILE_WriteLine( hFile, buffer, len, encoding );
246         HeapFree(GetProcessHeap(), 0, buffer);
247     }
248 }
249
250
251 /***********************************************************************
252  *           PROFILE_Free
253  *
254  * Free a profile tree.
255  */
256 static void PROFILE_Free( PROFILESECTION *section )
257 {
258     PROFILESECTION *next_section;
259     PROFILEKEY *key, *next_key;
260
261     for ( ; section; section = next_section)
262     {
263         for (key = section->key; key; key = next_key)
264         {
265             next_key = key->next;
266             HeapFree( GetProcessHeap(), 0, key->value );
267             HeapFree( GetProcessHeap(), 0, key );
268         }
269         next_section = section->next;
270         HeapFree( GetProcessHeap(), 0, section );
271     }
272 }
273
274 /* returns 1 if a character white space else 0 */
275 static inline int PROFILE_isspaceW(WCHAR c)
276 {
277         if (isspaceW(c)) return 1;
278         if (c=='\r' || c==0x1a) return 1;
279         /* CR and ^Z (DOS EOF) are spaces too  (found on CD-ROMs) */
280         return 0;
281 }
282
283 static inline ENCODING PROFILE_DetectTextEncoding(const void * buffer, int * len)
284 {
285     int flags = IS_TEXT_UNICODE_SIGNATURE |
286                 IS_TEXT_UNICODE_REVERSE_SIGNATURE |
287                 IS_TEXT_UNICODE_ODD_LENGTH;
288     if (*len >= sizeof(bom_utf8) && !memcmp(buffer, bom_utf8, sizeof(bom_utf8)))
289     {
290         *len = sizeof(bom_utf8);
291         return ENCODING_UTF8;
292     }
293     RtlIsTextUnicode(buffer, *len, &flags);
294     if (flags & IS_TEXT_UNICODE_SIGNATURE)
295     {
296         *len = sizeof(WCHAR);
297         return ENCODING_UTF16LE;
298     }
299     if (flags & IS_TEXT_UNICODE_REVERSE_SIGNATURE)
300     {
301         *len = sizeof(WCHAR);
302         return ENCODING_UTF16BE;
303     }
304     *len = 0;
305     return ENCODING_ANSI;
306 }
307
308 static const WCHAR * PROFILE_GetLine(const WCHAR * szStart, const WCHAR * szEnd)
309 {
310     return memchrW(szStart, '\n', szEnd - szStart);
311 }
312
313 /***********************************************************************
314  *           PROFILE_Load
315  *
316  * Load a profile tree from a file.
317  */
318 static PROFILESECTION *PROFILE_Load(HANDLE hFile, ENCODING * pEncoding)
319 {
320     void *pBuffer;
321     WCHAR * szFile;
322     const WCHAR *szLineStart, *szLineEnd;
323     const WCHAR *szValueStart, *szNameEnd, *szEnd;
324     int line = 0, len;
325     PROFILESECTION *section, *first_section;
326     PROFILESECTION **next_section;
327     PROFILEKEY *key, *prev_key, **next_key;
328     DWORD dwFileSize;
329     
330     TRACE("%p\n", hFile);
331     
332     dwFileSize = GetFileSize(hFile, NULL);
333     if (dwFileSize == INVALID_FILE_SIZE)
334         return NULL;
335
336     pBuffer = HeapAlloc(GetProcessHeap(), 0 , dwFileSize);
337     if (!pBuffer) return NULL;
338     
339     if (!ReadFile(hFile, pBuffer, dwFileSize, &dwFileSize, NULL))
340     {
341         HeapFree(GetProcessHeap(), 0, pBuffer);
342         WARN("Error %ld reading file\n", GetLastError());
343         return NULL;
344     }
345     len = dwFileSize;
346     *pEncoding = PROFILE_DetectTextEncoding(pBuffer, &len);
347     /* len is set to the number of bytes in the character marker.
348      * we want to skip these bytes */
349     pBuffer = (char *)pBuffer + len;
350     dwFileSize -= len;
351     switch (*pEncoding)
352     {
353     case ENCODING_ANSI:
354         TRACE("ANSI encoding\n");
355
356         len = MultiByteToWideChar(CP_ACP, 0, (char *)pBuffer, dwFileSize, NULL, 0);
357         szFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
358         if (!szFile)
359         {
360             HeapFree(GetProcessHeap(), 0, pBuffer);
361             return NULL;
362         }
363         MultiByteToWideChar(CP_ACP, 0, (char *)pBuffer, dwFileSize, szFile, len);
364         szEnd = szFile + len;
365         break;
366     case ENCODING_UTF8:
367         TRACE("UTF8 encoding\n");
368         
369         len = MultiByteToWideChar(CP_UTF8, 0, (char *)pBuffer, dwFileSize, NULL, 0);
370         szFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
371         if (!szFile)
372         {
373             HeapFree(GetProcessHeap(), 0, pBuffer);
374             return NULL;
375         }
376         MultiByteToWideChar(CP_UTF8, 0, (char *)pBuffer, dwFileSize, szFile, len);
377         szEnd = szFile + len;
378         break;
379     case ENCODING_UTF16LE:
380         TRACE("UTF16 Little Endian encoding\n");
381         szFile = (WCHAR *)pBuffer + 1;
382         szEnd = (WCHAR *)((char *)pBuffer + dwFileSize);
383         break;
384     case ENCODING_UTF16BE:
385         TRACE("UTF16 Big Endian encoding\n");
386         szFile = (WCHAR *)pBuffer + 1;
387         szEnd = (WCHAR *)((char *)pBuffer + dwFileSize);
388         PROFILE_ByteSwapShortBuffer(szFile, dwFileSize / sizeof(WCHAR));
389         break;
390     default:
391         FIXME("encoding type %d not implemented\n", *pEncoding);
392         HeapFree(GetProcessHeap(), 0, pBuffer);
393         return NULL;
394     }
395
396     first_section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) );
397     if(first_section == NULL)
398     {
399         if (szFile != pBuffer)
400             HeapFree(GetProcessHeap(), 0, szFile);
401         HeapFree(GetProcessHeap(), 0, pBuffer);
402         return NULL;
403     }
404     first_section->name[0] = 0;
405     first_section->key  = NULL;
406     first_section->next = NULL;
407     next_section = &first_section->next;
408     next_key     = &first_section->key;
409     prev_key     = NULL;
410     szLineEnd = szFile - 1; /* will be increased to correct value in loop */
411
412     while (TRUE)
413     {
414         szLineStart = szLineEnd + 1;
415         if (szLineStart >= szEnd)
416             break;
417         szLineEnd = PROFILE_GetLine(szLineStart, szEnd);
418         if (!szLineEnd)
419             szLineEnd = szEnd;
420         line++;
421         
422         while (szLineStart < szLineEnd && PROFILE_isspaceW(*szLineStart)) szLineStart++;
423         
424         if (szLineStart >= szLineEnd) continue;
425
426         if (*szLineStart == '[')  /* section start */
427         {
428             const WCHAR * szSectionEnd;
429             if (!(szSectionEnd = memrchrW( szLineStart, ']', szLineEnd - szLineStart )))
430             {
431                 WARN("Invalid section header at line %d: %s\n",
432                     line, debugstr_wn(szLineStart, (int)(szLineEnd - szLineStart)) );
433             }
434             else
435             {
436                 szLineStart++;
437                 len = (int)(szSectionEnd - szLineStart);
438                 /* no need to allocate +1 for NULL terminating character as
439                  * already included in structure */
440                 if (!(section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) + len * sizeof(WCHAR) )))
441                     break;
442                 memcpy(section->name, szLineStart, len * sizeof(WCHAR));
443                 section->name[len] = '\0';
444                 section->key  = NULL;
445                 section->next = NULL;
446                 *next_section = section;
447                 next_section  = &section->next;
448                 next_key      = &section->key;
449                 prev_key      = NULL;
450
451                 TRACE("New section: %s\n", debugstr_w(section->name));
452
453                 continue;
454             }
455         }
456
457         /* get rid of white space at the end of the line */
458         while ((szLineEnd > szLineStart) && ((*szLineEnd == '\n') || PROFILE_isspaceW(*szLineEnd))) szLineEnd--;
459
460         /* line end should be pointing to character *after* the last wanted character */
461         szLineEnd++;
462
463         /* get rid of white space after the name and before the start
464          * of the value */
465         if ((szNameEnd = szValueStart = memchrW( szLineStart, '=', szLineEnd - szLineStart )) != NULL)
466         {
467             szNameEnd = szValueStart - 1;
468             while ((szNameEnd > szLineStart) && PROFILE_isspaceW(*szNameEnd)) szNameEnd--;
469             szValueStart++;
470             while (szValueStart < szLineEnd && PROFILE_isspaceW(*szValueStart)) szValueStart++;
471         }
472         if (!szNameEnd)
473             szNameEnd = szLineEnd - 1;
474         /* name end should be pointing to character *after* the last wanted character */
475         szNameEnd++;
476
477         len = (int)(szNameEnd - szLineStart);
478         
479         if (len || !prev_key || *prev_key->name)
480         {
481             /* no need to allocate +1 for NULL terminating character as
482              * already included in structure */
483             if (!(key = HeapAlloc( GetProcessHeap(), 0, sizeof(*key) + len * sizeof(WCHAR) ))) break;
484             memcpy(key->name, szLineStart, len * sizeof(WCHAR));
485             key->name[len] = '\0';
486             if (szValueStart)
487             {
488                 len = (int)(szLineEnd - szValueStart);
489                 key->value = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
490                 memcpy(key->value, szValueStart, len * sizeof(WCHAR));
491                 key->value[len] = '\0';
492             }
493             else key->value = NULL;
494
495            key->next  = NULL;
496            *next_key  = key;
497            next_key   = &key->next;
498            prev_key   = key;
499
500            TRACE("New key: name=%s, value=%s\n",
501                debugstr_w(key->name), key->value ? debugstr_w(key->value) : "(none)");
502         }
503     }
504     if (szFile != pBuffer)
505         HeapFree(GetProcessHeap(), 0, szFile);
506     HeapFree(GetProcessHeap(), 0, pBuffer);
507     return first_section;
508 }
509
510
511 /***********************************************************************
512  *           PROFILE_DeleteSection
513  *
514  * Delete a section from a profile tree.
515  */
516 static BOOL PROFILE_DeleteSection( PROFILESECTION **section, LPCWSTR name )
517 {
518     while (*section)
519     {
520         if ((*section)->name[0] && !strcmpiW( (*section)->name, name ))
521         {
522             PROFILESECTION *to_del = *section;
523             *section = to_del->next;
524             to_del->next = NULL;
525             PROFILE_Free( to_del );
526             return TRUE;
527         }
528         section = &(*section)->next;
529     }
530     return FALSE;
531 }
532
533
534 /***********************************************************************
535  *           PROFILE_DeleteKey
536  *
537  * Delete a key from a profile tree.
538  */
539 static BOOL PROFILE_DeleteKey( PROFILESECTION **section,
540                                LPCWSTR section_name, LPCWSTR key_name )
541 {
542     while (*section)
543     {
544         if ((*section)->name[0] && !strcmpiW( (*section)->name, section_name ))
545         {
546             PROFILEKEY **key = &(*section)->key;
547             while (*key)
548             {
549                 if (!strcmpiW( (*key)->name, key_name ))
550                 {
551                     PROFILEKEY *to_del = *key;
552                     *key = to_del->next;
553                     HeapFree( GetProcessHeap(), 0, to_del->value);
554                     HeapFree( GetProcessHeap(), 0, to_del );
555                     return TRUE;
556                 }
557                 key = &(*key)->next;
558             }
559         }
560         section = &(*section)->next;
561     }
562     return FALSE;
563 }
564
565
566 /***********************************************************************
567  *           PROFILE_DeleteAllKeys
568  *
569  * Delete all keys from a profile tree.
570  */
571 void PROFILE_DeleteAllKeys( LPCWSTR section_name)
572 {
573     PROFILESECTION **section= &CurProfile->section;
574     while (*section)
575     {
576         if ((*section)->name[0] && !strcmpiW( (*section)->name, section_name ))
577         {
578             PROFILEKEY **key = &(*section)->key;
579             while (*key)
580             {
581                 PROFILEKEY *to_del = *key;
582                 *key = to_del->next;
583                 HeapFree( GetProcessHeap(), 0, to_del->value);
584                 HeapFree( GetProcessHeap(), 0, to_del );
585                 CurProfile->changed =TRUE;
586             }
587         }
588         section = &(*section)->next;
589     }
590 }
591
592
593 /***********************************************************************
594  *           PROFILE_Find
595  *
596  * Find a key in a profile tree, optionally creating it.
597  */
598 static PROFILEKEY *PROFILE_Find( PROFILESECTION **section, LPCWSTR section_name,
599                                  LPCWSTR key_name, BOOL create, BOOL create_always )
600 {
601     LPCWSTR p;
602     int seclen, keylen;
603
604     while (PROFILE_isspaceW(*section_name)) section_name++;
605     p = section_name + strlenW(section_name) - 1;
606     while ((p > section_name) && PROFILE_isspaceW(*p)) p--;
607     seclen = p - section_name + 1;
608
609     while (PROFILE_isspaceW(*key_name)) key_name++;
610     p = key_name + strlenW(key_name) - 1;
611     while ((p > key_name) && PROFILE_isspaceW(*p)) p--;
612     keylen = p - key_name + 1;
613
614     while (*section)
615     {
616         if ( ((*section)->name[0])
617              && (!(strncmpiW( (*section)->name, section_name, seclen )))
618              && (((*section)->name)[seclen] == '\0') )
619         {
620             PROFILEKEY **key = &(*section)->key;
621
622             while (*key)
623             {
624                 /* If create_always is FALSE then we check if the keyname
625                  * already exists. Otherwise we add it regardless of its
626                  * existence, to allow keys to be added more than once in
627                  * some cases.
628                  */
629                 if(!create_always)
630                 {
631                     if ( (!(strncmpiW( (*key)->name, key_name, keylen )))
632                          && (((*key)->name)[keylen] == '\0') )
633                         return *key;
634                 }
635                 key = &(*key)->next;
636             }
637             if (!create) return NULL;
638             if (!(*key = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
639                 return NULL;
640             strcpyW( (*key)->name, key_name );
641             (*key)->value = NULL;
642             (*key)->next  = NULL;
643             return *key;
644         }
645         section = &(*section)->next;
646     }
647     if (!create) return NULL;
648     *section = HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILESECTION) + strlenW(section_name) * sizeof(WCHAR) );
649     if(*section == NULL) return NULL;
650     strcpyW( (*section)->name, section_name );
651     (*section)->next = NULL;
652     if (!((*section)->key  = HeapAlloc( GetProcessHeap(), 0,
653                                         sizeof(PROFILEKEY) + strlenW(key_name) * sizeof(WCHAR) )))
654     {
655         HeapFree(GetProcessHeap(), 0, *section);
656         return NULL;
657     }
658     strcpyW( (*section)->key->name, key_name );
659     (*section)->key->value = NULL;
660     (*section)->key->next  = NULL;
661     return (*section)->key;
662 }
663
664
665 /***********************************************************************
666  *           PROFILE_FlushFile
667  *
668  * Flush the current profile to disk if changed.
669  */
670 static BOOL PROFILE_FlushFile(void)
671 {
672     HANDLE hFile = NULL;
673     FILETIME LastWriteTime;
674
675     if(!CurProfile)
676     {
677         WARN("No current profile!\n");
678         return FALSE;
679     }
680
681     if (!CurProfile->changed) return TRUE;
682
683     hFile = CreateFileW(CurProfile->filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
684
685     if (hFile == INVALID_HANDLE_VALUE)
686     {
687         WARN("could not save profile file %s (error was %ld)\n", debugstr_w(CurProfile->filename), GetLastError());
688         return FALSE;
689     }
690
691     TRACE("Saving %s\n", debugstr_w(CurProfile->filename));
692     PROFILE_Save( hFile, CurProfile->section, CurProfile->encoding );
693     if(GetFileTime(hFile, NULL, NULL, &LastWriteTime))
694        CurProfile->LastWriteTime=LastWriteTime;
695     CloseHandle( hFile );
696     CurProfile->changed = FALSE;
697     return TRUE;
698 }
699
700
701 /***********************************************************************
702  *           PROFILE_ReleaseFile
703  *
704  * Flush the current profile to disk and remove it from the cache.
705  */
706 static void PROFILE_ReleaseFile(void)
707 {
708     PROFILE_FlushFile();
709     PROFILE_Free( CurProfile->section );
710     HeapFree( GetProcessHeap(), 0, CurProfile->filename );
711     CurProfile->changed = FALSE;
712     CurProfile->section = NULL;
713     CurProfile->filename  = NULL;
714     CurProfile->encoding = ENCODING_ANSI;
715     ZeroMemory(&CurProfile->LastWriteTime, sizeof(CurProfile->LastWriteTime));
716 }
717
718
719 /***********************************************************************
720  *           PROFILE_Open
721  *
722  * Open a profile file, checking the cached file first.
723  */
724 static BOOL PROFILE_Open( LPCWSTR filename )
725 {
726     WCHAR windirW[MAX_PATH];
727     WCHAR buffer[MAX_PATH];
728     HANDLE hFile = INVALID_HANDLE_VALUE;
729     FILETIME LastWriteTime;
730     int i,j;
731     PROFILE *tempProfile;
732     
733     ZeroMemory(&LastWriteTime, sizeof(LastWriteTime));
734
735     /* First time around */
736
737     if(!CurProfile)
738        for(i=0;i<N_CACHED_PROFILES;i++)
739        {
740           MRUProfile[i]=HeapAlloc( GetProcessHeap(), 0, sizeof(PROFILE) );
741           if(MRUProfile[i] == NULL) break;
742           MRUProfile[i]->changed=FALSE;
743           MRUProfile[i]->section=NULL;
744           MRUProfile[i]->filename=NULL;
745           MRUProfile[i]->encoding=ENCODING_ANSI;
746           ZeroMemory(&MRUProfile[i]->LastWriteTime, sizeof(FILETIME));
747        }
748
749     GetWindowsDirectoryW( windirW, MAX_PATH );
750
751     if ((RtlDetermineDosPathNameType_U(filename) == RELATIVE_PATH) &&
752         !strchrW(filename, '\\') && !strchrW(filename, '/'))
753     {
754         static const WCHAR wszSeparator[] = {'\\', 0};
755         strcpyW(buffer, windirW);
756         strcatW(buffer, wszSeparator);
757         strcatW(buffer, filename);
758     }
759     else
760     {
761         LPWSTR dummy;
762         GetFullPathNameW(filename, sizeof(buffer)/sizeof(buffer[0]), buffer, &dummy);
763     }
764         
765     TRACE("path: %s\n", debugstr_w(buffer));
766     
767     hFile = CreateFileW(buffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
768     
769     if ((hFile == INVALID_HANDLE_VALUE) && (GetLastError() != ERROR_FILE_NOT_FOUND))
770     {
771         WARN("Error %ld opening file %s\n", GetLastError(), debugstr_w(buffer));
772         return FALSE;
773     }
774
775     for(i=0;i<N_CACHED_PROFILES;i++)
776     {
777         if ((MRUProfile[i]->filename && !strcmpiW( buffer, MRUProfile[i]->filename )))
778         {
779             TRACE("MRU Filename: %s, new filename: %s\n", debugstr_w(MRUProfile[i]->filename), debugstr_w(buffer));
780             if(i)
781             {
782                 PROFILE_FlushFile();
783                 tempProfile=MRUProfile[i];
784                 for(j=i;j>0;j--)
785                     MRUProfile[j]=MRUProfile[j-1];
786                 CurProfile=tempProfile;
787             }
788
789             if (hFile != INVALID_HANDLE_VALUE)
790             {
791                 if (TRACE_ON(profile))
792                 {
793                     GetFileTime(hFile, NULL, NULL, &LastWriteTime);
794                     if (memcmp(&CurProfile->LastWriteTime, &LastWriteTime, sizeof(FILETIME)))
795                         TRACE("(%s): already opened (mru=%d)\n",
796                               debugstr_w(buffer), i);
797                     else
798                         TRACE("(%s): already opened, needs refreshing (mru=%d)\n",
799                               debugstr_w(buffer), i);
800                 }
801                 CloseHandle(hFile);
802             }
803             else TRACE("(%s): already opened, not yet created (mru=%d)\n",
804                        debugstr_w(buffer), i);
805             return TRUE;
806         }
807     }
808
809     /* Flush the old current profile */
810     PROFILE_FlushFile();
811
812     /* Make the oldest profile the current one only in order to get rid of it */
813     if(i==N_CACHED_PROFILES)
814       {
815        tempProfile=MRUProfile[N_CACHED_PROFILES-1];
816        for(i=N_CACHED_PROFILES-1;i>0;i--)
817           MRUProfile[i]=MRUProfile[i-1];
818        CurProfile=tempProfile;
819       }
820     if(CurProfile->filename) PROFILE_ReleaseFile();
821
822     /* OK, now that CurProfile is definitely free we assign it our new file */
823     CurProfile->filename  = HeapAlloc( GetProcessHeap(), 0, (strlenW(buffer)+1) * sizeof(WCHAR) );
824     strcpyW( CurProfile->filename, buffer );
825
826     if (hFile != INVALID_HANDLE_VALUE)
827     {
828         CurProfile->section = PROFILE_Load(hFile, &CurProfile->encoding);
829         GetFileTime(hFile, NULL, NULL, &CurProfile->LastWriteTime);
830         CloseHandle(hFile);
831     }
832     else
833     {
834         /* Does not exist yet, we will create it in PROFILE_FlushFile */
835         WARN("profile file %s not found\n", debugstr_w(buffer) );
836     }
837     return TRUE;
838 }
839
840
841 /***********************************************************************
842  *           PROFILE_GetSection
843  *
844  * Returns all keys of a section.
845  * If return_values is TRUE, also include the corresponding values.
846  */
847 static INT PROFILE_GetSection( PROFILESECTION *section, LPCWSTR section_name,
848                                LPWSTR buffer, UINT len, BOOL return_values )
849 {
850     PROFILEKEY *key;
851
852     if(!buffer) return 0;
853
854     TRACE("%s,%p,%u\n", debugstr_w(section_name), buffer, len);
855
856     while (section)
857     {
858         if (section->name[0] && !strcmpiW( section->name, section_name ))
859         {
860             UINT oldlen = len;
861             for (key = section->key; key; key = key->next)
862             {
863                 if (len <= 2) break;
864                 if (!*key->name) continue;  /* Skip empty lines */
865                 if (IS_ENTRY_COMMENT(key->name)) continue;  /* Skip comments */
866                 if (!return_values && !key->value) continue;  /* Skip lines w.o. '=' */
867                 PROFILE_CopyEntry( buffer, key->name, len - 1, 0 );
868                 len -= strlenW(buffer) + 1;
869                 buffer += strlenW(buffer) + 1;
870                 if (len < 2)
871                     break;
872                 if (return_values && key->value) {
873                         buffer[-1] = '=';
874                         PROFILE_CopyEntry ( buffer, key->value, len - 1, 0 );
875                         len -= strlenW(buffer) + 1;
876                         buffer += strlenW(buffer) + 1;
877                 }
878             }
879             *buffer = '\0';
880             if (len <= 1)
881                 /*If either lpszSection or lpszKey is NULL and the supplied
882                   destination buffer is too small to hold all the strings,
883                   the last string is truncated and followed by two null characters.
884                   In this case, the return value is equal to cchReturnBuffer
885                   minus two. */
886             {
887                 buffer[-1] = '\0';
888                 return oldlen - 2;
889             }
890             return oldlen - len;
891         }
892         section = section->next;
893     }
894     buffer[0] = buffer[1] = '\0';
895     return 0;
896 }
897
898 /* See GetPrivateProfileSectionNamesA for documentation */
899 static INT PROFILE_GetSectionNames( LPWSTR buffer, UINT len )
900 {
901     LPWSTR buf;
902     UINT buflen,tmplen;
903     PROFILESECTION *section;
904
905     TRACE("(%p, %d)\n", buffer, len);
906
907     if (!buffer || !len)
908         return 0;
909     if (len==1) {
910         *buffer='\0';
911         return 0;
912     }
913
914     buflen=len-1;
915     buf=buffer;
916     section = CurProfile->section;
917     while ((section!=NULL)) {
918         if (section->name[0]) {
919             tmplen = strlenW(section->name)+1;
920             if (tmplen > buflen) {
921                 if (buflen > 0) {
922                     memcpy(buf, section->name, (buflen-1) * sizeof(WCHAR));
923                     buf += buflen-1;
924                     *buf++='\0';
925                 }
926                 *buf='\0';
927                 return len-2;
928             }
929             memcpy(buf, section->name, tmplen * sizeof(WCHAR));
930             buf += tmplen;
931             buflen -= tmplen;
932         }
933         section = section->next;
934     }
935     *buf='\0';
936     return buf-buffer;
937 }
938
939
940 /***********************************************************************
941  *           PROFILE_GetString
942  *
943  * Get a profile string.
944  *
945  * Tests with GetPrivateProfileString16, W95a,
946  * with filled buffer ("****...") and section "set1" and key_name "1" valid:
947  * section      key_name        def_val         res     buffer
948  * "set1"       "1"             "x"             43      [data]
949  * "set1"       "1   "          "x"             43      [data]          (!)
950  * "set1"       "  1  "'        "x"             43      [data]          (!)
951  * "set1"       ""              "x"             1       "x"
952  * "set1"       ""              "x   "          1       "x"             (!)
953  * "set1"       ""              "  x   "        3       "  x"           (!)
954  * "set1"       NULL            "x"             6       "1\02\03\0\0"
955  * "set1"       ""              "x"             1       "x"
956  * NULL         "1"             "x"             0       ""              (!)
957  * ""           "1"             "x"             1       "x"
958  * NULL         NULL            ""              0       ""
959  *
960  *
961  */
962 static INT PROFILE_GetString( LPCWSTR section, LPCWSTR key_name,
963                               LPCWSTR def_val, LPWSTR buffer, UINT len )
964 {
965     PROFILEKEY *key = NULL;
966     static const WCHAR empty_strW[] = { 0 };
967
968     if(!buffer) return 0;
969
970     if (!def_val) def_val = empty_strW;
971     if (key_name)
972     {
973         if (!key_name[0])
974         {
975             /* Win95 returns 0 on keyname "". Tested with Likse32 bon 000227 */
976             return 0;
977         }
978         key = PROFILE_Find( &CurProfile->section, section, key_name, FALSE, FALSE);
979         PROFILE_CopyEntry( buffer, (key && key->value) ? key->value : def_val,
980                            len, TRUE );
981         TRACE("(%s,%s,%s): returning %s\n",
982               debugstr_w(section), debugstr_w(key_name),
983               debugstr_w(def_val), debugstr_w(buffer) );
984         return strlenW( buffer );
985     }
986     /* no "else" here ! */
987     if (section && section[0])
988     {
989         INT ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, FALSE);
990         if (!buffer[0]) /* no luck -> def_val */
991         {
992             PROFILE_CopyEntry(buffer, def_val, len, TRUE);
993             ret = strlenW(buffer);
994         }
995         return ret;
996     }
997     buffer[0] = '\0';
998     return 0;
999 }
1000
1001
1002 /***********************************************************************
1003  *           PROFILE_SetString
1004  *
1005  * Set a profile string.
1006  */
1007 static BOOL PROFILE_SetString( LPCWSTR section_name, LPCWSTR key_name,
1008                                LPCWSTR value, BOOL create_always )
1009 {
1010     if (!key_name)  /* Delete a whole section */
1011     {
1012         TRACE("(%s)\n", debugstr_w(section_name));
1013         CurProfile->changed |= PROFILE_DeleteSection( &CurProfile->section,
1014                                                       section_name );
1015         return TRUE;         /* Even if PROFILE_DeleteSection() has failed,
1016                                 this is not an error on application's level.*/
1017     }
1018     else if (!value)  /* Delete a key */
1019     {
1020         TRACE("(%s,%s)\n", debugstr_w(section_name), debugstr_w(key_name) );
1021         CurProfile->changed |= PROFILE_DeleteKey( &CurProfile->section,
1022                                                   section_name, key_name );
1023         return TRUE;          /* same error handling as above */
1024     }
1025     else  /* Set the key value */
1026     {
1027         PROFILEKEY *key = PROFILE_Find(&CurProfile->section, section_name,
1028                                         key_name, TRUE, create_always );
1029         TRACE("(%s,%s,%s):\n",
1030               debugstr_w(section_name), debugstr_w(key_name), debugstr_w(value) );
1031         if (!key) return FALSE;
1032
1033         /* strip the leading spaces. We can safely strip \n\r and
1034          * friends too, they should not happen here anyway. */
1035         while (PROFILE_isspaceW(*value)) value++;
1036
1037         if (key->value)
1038         {
1039             if (!strcmpW( key->value, value ))
1040             {
1041                 TRACE("  no change needed\n" );
1042                 return TRUE;  /* No change needed */
1043             }
1044             TRACE("  replacing %s\n", debugstr_w(key->value) );
1045             HeapFree( GetProcessHeap(), 0, key->value );
1046         }
1047         else TRACE("  creating key\n" );
1048         key->value = HeapAlloc( GetProcessHeap(), 0, (strlenW(value)+1) * sizeof(WCHAR) );
1049         strcpyW( key->value, value );
1050         CurProfile->changed = TRUE;
1051     }
1052     return TRUE;
1053 }
1054
1055
1056 /********************* API functions **********************************/
1057
1058
1059 /***********************************************************************
1060  *           GetProfileIntA   (KERNEL32.@)
1061  */
1062 UINT WINAPI GetProfileIntA( LPCSTR section, LPCSTR entry, INT def_val )
1063 {
1064     return GetPrivateProfileIntA( section, entry, def_val, "win.ini" );
1065 }
1066
1067 /***********************************************************************
1068  *           GetProfileIntW   (KERNEL32.@)
1069  */
1070 UINT WINAPI GetProfileIntW( LPCWSTR section, LPCWSTR entry, INT def_val )
1071 {
1072     return GetPrivateProfileIntW( section, entry, def_val, wininiW );
1073 }
1074
1075 /*
1076  * if allow_section_name_copy is TRUE, allow the copying :
1077  *   - of Section names if 'section' is NULL
1078  *   - of Keys in a Section if 'entry' is NULL
1079  * (see MSDN doc for GetPrivateProfileString)
1080  */
1081 static int PROFILE_GetPrivateProfileString( LPCWSTR section, LPCWSTR entry,
1082                                             LPCWSTR def_val, LPWSTR buffer,
1083                                             UINT len, LPCWSTR filename,
1084                                             BOOL allow_section_name_copy )
1085 {
1086     int         ret;
1087     LPCWSTR     pDefVal = NULL;
1088
1089     if (!filename)
1090         filename = wininiW;
1091
1092     TRACE("%s,%s,%s,%p,%u,%s\n", debugstr_w(section), debugstr_w(entry),
1093           debugstr_w(def_val), buffer, len, debugstr_w(filename));
1094
1095     /* strip any trailing ' ' of def_val. */
1096     if (def_val)
1097     {
1098         LPCWSTR p = &def_val[strlenW(def_val)]; /* even "" works ! */
1099
1100         while (p > def_val)
1101         {
1102             p--;
1103             if ((*p) != ' ')
1104                 break;
1105         }
1106         if (*p == ' ') /* ouch, contained trailing ' ' */
1107         {
1108             int len = (int)(p - def_val);
1109             LPWSTR p;
1110
1111             p = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1112             memcpy(p, def_val, len * sizeof(WCHAR));
1113             p[len] = '\0';
1114             pDefVal = p;
1115         }
1116     }
1117     if (!pDefVal)
1118         pDefVal = (LPCWSTR)def_val;
1119
1120     RtlEnterCriticalSection( &PROFILE_CritSect );
1121
1122     if (PROFILE_Open( filename )) {
1123         if ((allow_section_name_copy) && (section == NULL))
1124             ret = PROFILE_GetSectionNames(buffer, len);
1125         else
1126             /* PROFILE_GetString already handles the 'entry == NULL' case */
1127             ret = PROFILE_GetString( section, entry, pDefVal, buffer, len );
1128     } else {
1129        lstrcpynW( buffer, pDefVal, len );
1130        ret = strlenW( buffer );
1131     }
1132
1133     RtlLeaveCriticalSection( &PROFILE_CritSect );
1134
1135     if (pDefVal != def_val) /* allocated */
1136         HeapFree(GetProcessHeap(), 0, (void*)pDefVal);
1137
1138     TRACE("returning %s, %d\n", debugstr_w(buffer), ret);
1139
1140     return ret;
1141 }
1142
1143 /***********************************************************************
1144  *           GetPrivateProfileString   (KERNEL.128)
1145  */
1146 INT16 WINAPI GetPrivateProfileString16( LPCSTR section, LPCSTR entry,
1147                                         LPCSTR def_val, LPSTR buffer,
1148                                         UINT16 len, LPCSTR filename )
1149 {
1150     UNICODE_STRING sectionW, entryW, def_valW, filenameW;
1151     LPWSTR bufferW;
1152     INT16 retW, ret = 0;
1153
1154     bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)) : NULL;
1155     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1156     else sectionW.Buffer = NULL;
1157     if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1158     else entryW.Buffer = NULL;
1159     if (def_val) RtlCreateUnicodeStringFromAsciiz(&def_valW, def_val);
1160     else def_valW.Buffer = NULL;
1161     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1162     else filenameW.Buffer = NULL;
1163
1164     retW = PROFILE_GetPrivateProfileString( sectionW.Buffer, entryW.Buffer,
1165                                      def_valW.Buffer, bufferW, len,
1166                                      filenameW.Buffer, FALSE );
1167     if (len)
1168     {
1169         ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW + 1, buffer, len, NULL, NULL);
1170         if (!ret)
1171         {
1172             ret = len - 1;
1173             buffer[ret] = 0;
1174         }
1175         else
1176             ret--; /* strip terminating 0 */
1177     }
1178
1179     RtlFreeUnicodeString(&sectionW);
1180     RtlFreeUnicodeString(&entryW);
1181     RtlFreeUnicodeString(&def_valW);
1182     RtlFreeUnicodeString(&filenameW);
1183     HeapFree(GetProcessHeap(), 0, bufferW);
1184     return ret;
1185 }
1186
1187 /***********************************************************************
1188  *           GetPrivateProfileStringA   (KERNEL32.@)
1189  */
1190 INT WINAPI GetPrivateProfileStringA( LPCSTR section, LPCSTR entry,
1191                                      LPCSTR def_val, LPSTR buffer,
1192                                      UINT len, LPCSTR filename )
1193 {
1194     UNICODE_STRING sectionW, entryW, def_valW, filenameW;
1195     LPWSTR bufferW;
1196     INT retW, ret = 0;
1197
1198     bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)) : NULL;
1199     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1200     else sectionW.Buffer = NULL;
1201     if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1202     else entryW.Buffer = NULL;
1203     if (def_val) RtlCreateUnicodeStringFromAsciiz(&def_valW, def_val);
1204     else def_valW.Buffer = NULL;
1205     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1206     else filenameW.Buffer = NULL;
1207
1208     retW = GetPrivateProfileStringW( sectionW.Buffer, entryW.Buffer,
1209                                      def_valW.Buffer, bufferW, len,
1210                                      filenameW.Buffer);
1211     if (len)
1212     {
1213         ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW + 1, buffer, len, NULL, NULL);
1214         if (!ret)
1215         {
1216             ret = len - 1;
1217             buffer[ret] = 0;
1218         }
1219         else
1220             ret--; /* strip terminating 0 */
1221     }
1222
1223     RtlFreeUnicodeString(&sectionW);
1224     RtlFreeUnicodeString(&entryW);
1225     RtlFreeUnicodeString(&def_valW);
1226     RtlFreeUnicodeString(&filenameW);
1227     HeapFree(GetProcessHeap(), 0, bufferW);
1228     return ret;
1229 }
1230
1231 /***********************************************************************
1232  *           GetPrivateProfileStringW   (KERNEL32.@)
1233  */
1234 INT WINAPI GetPrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1235                                      LPCWSTR def_val, LPWSTR buffer,
1236                                      UINT len, LPCWSTR filename )
1237 {
1238     TRACE("(%s, %s, %s, %p, %d, %s)\n", debugstr_w(section), debugstr_w(entry), debugstr_w(def_val), buffer, len, debugstr_w(filename));
1239
1240     return PROFILE_GetPrivateProfileString( section, entry, def_val,
1241                                             buffer, len, filename, TRUE );
1242 }
1243
1244 /***********************************************************************
1245  *           GetProfileStringA   (KERNEL32.@)
1246  */
1247 INT WINAPI GetProfileStringA( LPCSTR section, LPCSTR entry, LPCSTR def_val,
1248                               LPSTR buffer, UINT len )
1249 {
1250     return GetPrivateProfileStringA( section, entry, def_val,
1251                                      buffer, len, "win.ini" );
1252 }
1253
1254 /***********************************************************************
1255  *           GetProfileStringW   (KERNEL32.@)
1256  */
1257 INT WINAPI GetProfileStringW( LPCWSTR section, LPCWSTR entry,
1258                               LPCWSTR def_val, LPWSTR buffer, UINT len )
1259 {
1260     return GetPrivateProfileStringW( section, entry, def_val,
1261                                      buffer, len, wininiW );
1262 }
1263
1264 /***********************************************************************
1265  *           WriteProfileStringA   (KERNEL32.@)
1266  */
1267 BOOL WINAPI WriteProfileStringA( LPCSTR section, LPCSTR entry,
1268                                  LPCSTR string )
1269 {
1270     return WritePrivateProfileStringA( section, entry, string, "win.ini" );
1271 }
1272
1273 /***********************************************************************
1274  *           WriteProfileStringW   (KERNEL32.@)
1275  */
1276 BOOL WINAPI WriteProfileStringW( LPCWSTR section, LPCWSTR entry,
1277                                      LPCWSTR string )
1278 {
1279     return WritePrivateProfileStringW( section, entry, string, wininiW );
1280 }
1281
1282
1283 /***********************************************************************
1284  *           GetPrivateProfileIntW   (KERNEL32.@)
1285  */
1286 UINT WINAPI GetPrivateProfileIntW( LPCWSTR section, LPCWSTR entry,
1287                                    INT def_val, LPCWSTR filename )
1288 {
1289     WCHAR buffer[30];
1290     UNICODE_STRING bufferW;
1291     INT len;
1292     ULONG result;
1293
1294     if (!(len = GetPrivateProfileStringW( section, entry, emptystringW,
1295                                           buffer, sizeof(buffer)/sizeof(WCHAR),
1296                                           filename )))
1297         return def_val;
1298
1299     if (len+1 == sizeof(buffer)/sizeof(WCHAR)) FIXME("result may be wrong!\n");
1300
1301     /* FIXME: if entry can be found but it's empty, then Win16 is
1302      * supposed to return 0 instead of def_val ! Difficult/problematic
1303      * to implement (every other failure also returns zero buffer),
1304      * thus wait until testing framework avail for making sure nothing
1305      * else gets broken that way. */
1306     if (!buffer[0]) return (UINT)def_val;
1307
1308     RtlInitUnicodeString( &bufferW, buffer );
1309     RtlUnicodeStringToInteger( &bufferW, 10, &result);
1310     return result;
1311 }
1312
1313 /***********************************************************************
1314  *           GetPrivateProfileIntA   (KERNEL32.@)
1315  *
1316  * FIXME: rewrite using unicode
1317  */
1318 UINT WINAPI GetPrivateProfileIntA( LPCSTR section, LPCSTR entry,
1319                                    INT def_val, LPCSTR filename )
1320 {
1321     UNICODE_STRING entryW, filenameW, sectionW;
1322     UINT res;
1323     if(entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1324     else entryW.Buffer = NULL;
1325     if(filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1326     else filenameW.Buffer = NULL;
1327     if(section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1328     else sectionW.Buffer = NULL;
1329     res = GetPrivateProfileIntW(sectionW.Buffer, entryW.Buffer, def_val,
1330                                 filenameW.Buffer);
1331     RtlFreeUnicodeString(&sectionW);
1332     RtlFreeUnicodeString(&filenameW);
1333     RtlFreeUnicodeString(&entryW);
1334     return res;
1335 }
1336
1337 /***********************************************************************
1338  *           GetPrivateProfileSectionW   (KERNEL32.@)
1339  */
1340 INT WINAPI GetPrivateProfileSectionW( LPCWSTR section, LPWSTR buffer,
1341                                       DWORD len, LPCWSTR filename )
1342 {
1343     int         ret = 0;
1344
1345     TRACE("(%s, %p, %ld, %s)\n", debugstr_w(section), buffer, len, debugstr_w(filename));
1346
1347     RtlEnterCriticalSection( &PROFILE_CritSect );
1348
1349     if (PROFILE_Open( filename ))
1350         ret = PROFILE_GetSection(CurProfile->section, section, buffer, len, TRUE);
1351
1352     RtlLeaveCriticalSection( &PROFILE_CritSect );
1353
1354     return ret;
1355 }
1356
1357 /***********************************************************************
1358  *           GetPrivateProfileSectionA   (KERNEL32.@)
1359  */
1360 INT WINAPI GetPrivateProfileSectionA( LPCSTR section, LPSTR buffer,
1361                                       DWORD len, LPCSTR filename )
1362 {
1363     UNICODE_STRING sectionW, filenameW;
1364     LPWSTR bufferW;
1365     INT retW, ret = 0;
1366
1367     bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)) : NULL;
1368     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1369     else sectionW.Buffer = NULL;
1370     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1371     else filenameW.Buffer = NULL;
1372
1373     retW = GetPrivateProfileSectionW(sectionW.Buffer, bufferW, len, filenameW.Buffer);
1374     if (len > 2)
1375     {
1376         ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW + 2, buffer, len, NULL, NULL);
1377         if (ret > 2)
1378             ret -= 2;
1379         else
1380         {
1381             ret = 0;
1382             buffer[len-2] = 0;
1383             buffer[len-1] = 0;
1384         }
1385     }
1386     else
1387     {
1388         buffer[0] = 0;
1389         buffer[1] = 0;
1390     }
1391
1392     RtlFreeUnicodeString(&sectionW);
1393     RtlFreeUnicodeString(&filenameW);
1394     HeapFree(GetProcessHeap(), 0, bufferW);
1395     return ret;
1396 }
1397
1398 /***********************************************************************
1399  *           GetProfileSectionA   (KERNEL32.@)
1400  */
1401 INT WINAPI GetProfileSectionA( LPCSTR section, LPSTR buffer, DWORD len )
1402 {
1403     return GetPrivateProfileSectionA( section, buffer, len, "win.ini" );
1404 }
1405
1406 /***********************************************************************
1407  *           GetProfileSectionW   (KERNEL32.@)
1408  */
1409 INT WINAPI GetProfileSectionW( LPCWSTR section, LPWSTR buffer, DWORD len )
1410 {
1411     return GetPrivateProfileSectionW( section, buffer, len, wininiW );
1412 }
1413
1414
1415 /***********************************************************************
1416  *           WritePrivateProfileStringW   (KERNEL32.@)
1417  */
1418 BOOL WINAPI WritePrivateProfileStringW( LPCWSTR section, LPCWSTR entry,
1419                                         LPCWSTR string, LPCWSTR filename )
1420 {
1421     BOOL ret = FALSE;
1422
1423     RtlEnterCriticalSection( &PROFILE_CritSect );
1424
1425     if (!section && !entry && !string) /* documented "file flush" case */
1426     {
1427         if (!filename || PROFILE_Open( filename ))
1428         {
1429             if (CurProfile) PROFILE_ReleaseFile();  /* always return FALSE in this case */
1430         }
1431     }
1432     else if (PROFILE_Open( filename ))
1433     {
1434         if (!section) {
1435             FIXME("(NULL?,%s,%s,%s)?\n",
1436                   debugstr_w(entry), debugstr_w(string), debugstr_w(filename));
1437         } else {
1438             ret = PROFILE_SetString( section, entry, string, FALSE);
1439             PROFILE_FlushFile();
1440         }
1441     }
1442
1443     RtlLeaveCriticalSection( &PROFILE_CritSect );
1444     return ret;
1445 }
1446
1447 /***********************************************************************
1448  *           WritePrivateProfileStringA   (KERNEL32.@)
1449  */
1450 BOOL WINAPI WritePrivateProfileStringA( LPCSTR section, LPCSTR entry,
1451                                         LPCSTR string, LPCSTR filename )
1452 {
1453     UNICODE_STRING sectionW, entryW, stringW, filenameW;
1454     BOOL ret;
1455
1456     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1457     else sectionW.Buffer = NULL;
1458     if (entry) RtlCreateUnicodeStringFromAsciiz(&entryW, entry);
1459     else entryW.Buffer = NULL;
1460     if (string) RtlCreateUnicodeStringFromAsciiz(&stringW, string);
1461     else stringW.Buffer = NULL;
1462     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1463     else filenameW.Buffer = NULL;
1464
1465     ret = WritePrivateProfileStringW(sectionW.Buffer, entryW.Buffer,
1466                                      stringW.Buffer, filenameW.Buffer);
1467     RtlFreeUnicodeString(&sectionW);
1468     RtlFreeUnicodeString(&entryW);
1469     RtlFreeUnicodeString(&stringW);
1470     RtlFreeUnicodeString(&filenameW);
1471     return ret;
1472 }
1473
1474 /***********************************************************************
1475  *           WritePrivateProfileSectionW   (KERNEL32.@)
1476  */
1477 BOOL WINAPI WritePrivateProfileSectionW( LPCWSTR section,
1478                                          LPCWSTR string, LPCWSTR filename )
1479 {
1480     BOOL ret = FALSE;
1481     LPWSTR p;
1482
1483     RtlEnterCriticalSection( &PROFILE_CritSect );
1484
1485     if (!section && !string)
1486     {
1487         if (!filename || PROFILE_Open( filename ))
1488         {
1489             if (CurProfile) PROFILE_ReleaseFile();  /* always return FALSE in this case */
1490         }
1491     }
1492     else if (PROFILE_Open( filename )) {
1493         if (!string) {/* delete the named section*/
1494             ret = PROFILE_SetString(section,NULL,NULL, FALSE);
1495             PROFILE_FlushFile();
1496         } else {
1497             PROFILE_DeleteAllKeys(section);
1498             ret = TRUE;
1499             while(*string) {
1500                 LPWSTR buf = HeapAlloc( GetProcessHeap(), 0, (strlenW(string)+1) * sizeof(WCHAR) );
1501                 strcpyW( buf, string );
1502                 if((p = strchrW( buf, '='))) {
1503                     *p='\0';
1504                     ret = PROFILE_SetString( section, buf, p+1, TRUE);
1505                 }
1506                 HeapFree( GetProcessHeap(), 0, buf );
1507                 string += strlenW(string)+1;
1508             }
1509             PROFILE_FlushFile();
1510         }
1511     }
1512
1513     RtlLeaveCriticalSection( &PROFILE_CritSect );
1514     return ret;
1515 }
1516
1517 /***********************************************************************
1518  *           WritePrivateProfileSectionA   (KERNEL32.@)
1519  */
1520 BOOL WINAPI WritePrivateProfileSectionA( LPCSTR section,
1521                                          LPCSTR string, LPCSTR filename)
1522
1523 {
1524     UNICODE_STRING sectionW, filenameW;
1525     LPWSTR stringW;
1526     BOOL ret;
1527
1528     if (string)
1529     {
1530         INT lenA, lenW;
1531         LPCSTR p = string;
1532
1533         while(*p) p += strlen(p) + 1;
1534         lenA = p - string + 1;
1535         lenW = MultiByteToWideChar(CP_ACP, 0, string, lenA, NULL, 0);
1536         if ((stringW = HeapAlloc(GetProcessHeap(), 0, lenW * sizeof(WCHAR))))
1537             MultiByteToWideChar(CP_ACP, 0, string, lenA, stringW, lenW);
1538     }
1539     else stringW = NULL;
1540     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1541     else sectionW.Buffer = NULL;
1542     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1543     else filenameW.Buffer = NULL;
1544
1545     ret = WritePrivateProfileSectionW(sectionW.Buffer, stringW, filenameW.Buffer);
1546
1547     HeapFree(GetProcessHeap(), 0, stringW);
1548     RtlFreeUnicodeString(&sectionW);
1549     RtlFreeUnicodeString(&filenameW);
1550     return ret;
1551 }
1552
1553 /***********************************************************************
1554  *           WriteProfileSectionA   (KERNEL32.@)
1555  */
1556 BOOL WINAPI WriteProfileSectionA( LPCSTR section, LPCSTR keys_n_values)
1557
1558 {
1559     return WritePrivateProfileSectionA( section, keys_n_values, "win.ini");
1560 }
1561
1562 /***********************************************************************
1563  *           WriteProfileSectionW   (KERNEL32.@)
1564  */
1565 BOOL WINAPI WriteProfileSectionW( LPCWSTR section, LPCWSTR keys_n_values)
1566 {
1567    return WritePrivateProfileSectionW(section, keys_n_values, wininiW);
1568 }
1569
1570
1571 /***********************************************************************
1572  *           GetPrivateProfileSectionNamesW  (KERNEL32.@)
1573  *
1574  * Returns the section names contained in the specified file.
1575  * FIXME: Where do we find this file when the path is relative?
1576  * The section names are returned as a list of strings with an extra
1577  * '\0' to mark the end of the list. Except for that the behavior
1578  * depends on the Windows version.
1579  *
1580  * Win95:
1581  * - if the buffer is 0 or 1 character long then it is as if it was of
1582  *   infinite length.
1583  * - otherwise, if the buffer is too small only the section names that fit
1584  *   are returned.
1585  * - note that this means if the buffer was too small to return even just
1586  *   the first section name then a single '\0' will be returned.
1587  * - the return value is the number of characters written in the buffer,
1588  *   except if the buffer was too small in which case len-2 is returned
1589  *
1590  * Win2000:
1591  * - if the buffer is 0, 1 or 2 characters long then it is filled with
1592  *   '\0' and the return value is 0
1593  * - otherwise if the buffer is too small then the first section name that
1594  *   does not fit is truncated so that the string list can be terminated
1595  *   correctly (double '\0')
1596  * - the return value is the number of characters written in the buffer
1597  *   except for the trailing '\0'. If the buffer is too small, then the
1598  *   return value is len-2
1599  * - Win2000 has a bug that triggers when the section names and the
1600  *   trailing '\0' fit exactly in the buffer. In that case the trailing
1601  *   '\0' is missing.
1602  *
1603  * Wine implements the observed Win2000 behavior (except for the bug).
1604  *
1605  * Note that when the buffer is big enough then the return value may be any
1606  * value between 1 and len-1 (or len in Win95), including len-2.
1607  */
1608 DWORD WINAPI GetPrivateProfileSectionNamesW( LPWSTR buffer, DWORD size,
1609                                              LPCWSTR filename)
1610 {
1611     DWORD ret = 0;
1612
1613     RtlEnterCriticalSection( &PROFILE_CritSect );
1614
1615     if (PROFILE_Open( filename ))
1616         ret = PROFILE_GetSectionNames(buffer, size);
1617
1618     RtlLeaveCriticalSection( &PROFILE_CritSect );
1619
1620     return ret;
1621 }
1622
1623
1624 /***********************************************************************
1625  *           GetPrivateProfileSectionNamesA  (KERNEL32.@)
1626  */
1627 DWORD WINAPI GetPrivateProfileSectionNamesA( LPSTR buffer, DWORD size,
1628                                              LPCSTR filename)
1629 {
1630     UNICODE_STRING filenameW;
1631     LPWSTR bufferW;
1632     INT retW, ret = 0;
1633
1634     bufferW = buffer ? HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)) : NULL;
1635     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1636     else filenameW.Buffer = NULL;
1637
1638     retW = GetPrivateProfileSectionNamesW(bufferW, size, filenameW.Buffer);
1639     if (retW && size)
1640     {
1641         ret = WideCharToMultiByte(CP_ACP, 0, bufferW, retW, buffer, size, NULL, NULL);
1642         if (!ret)
1643         {
1644             ret = size;
1645             buffer[size-1] = 0;
1646         }
1647     }
1648
1649     RtlFreeUnicodeString(&filenameW);
1650     HeapFree(GetProcessHeap(), 0, bufferW);
1651     return ret;
1652 }
1653
1654 /***********************************************************************
1655  *           GetPrivateProfileStructW (KERNEL32.@)
1656  *
1657  * Should match Win95's behaviour pretty much
1658  */
1659 BOOL WINAPI GetPrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1660                                       LPVOID buf, UINT len, LPCWSTR filename)
1661 {
1662     BOOL        ret = FALSE;
1663
1664     RtlEnterCriticalSection( &PROFILE_CritSect );
1665
1666     if (PROFILE_Open( filename )) {
1667         PROFILEKEY *k = PROFILE_Find ( &CurProfile->section, section, key, FALSE, FALSE);
1668         if (k) {
1669             TRACE("value (at %p): %s\n", k->value, debugstr_w(k->value));
1670             if (((strlenW(k->value) - 2) / 2) == len)
1671             {
1672                 LPWSTR end, p;
1673                 BOOL valid = TRUE;
1674                 WCHAR c;
1675                 DWORD chksum = 0;
1676
1677                 end  = k->value + strlenW(k->value); /* -> '\0' */
1678                 /* check for invalid chars in ASCII coded hex string */
1679                 for (p=k->value; p < end; p++)
1680                 {
1681                     if (!isxdigitW(*p))
1682                     {
1683                         WARN("invalid char '%x' in file %s->[%s]->%s !\n",
1684                              *p, debugstr_w(filename), debugstr_w(section), debugstr_w(key));
1685                         valid = FALSE;
1686                         break;
1687                     }
1688                 }
1689                 if (valid)
1690                 {
1691                     BOOL highnibble = TRUE;
1692                     BYTE b = 0, val;
1693                     LPBYTE binbuf = (LPBYTE)buf;
1694
1695                     end -= 2; /* don't include checksum in output data */
1696                     /* translate ASCII hex format into binary data */
1697                     for (p=k->value; p < end; p++)
1698                     {
1699                         c = toupperW(*p);
1700                         val = (c > '9') ?
1701                                 (c - 'A' + 10) : (c - '0');
1702
1703                         if (highnibble)
1704                             b = val << 4;
1705                         else
1706                         {
1707                             b += val;
1708                             *binbuf++ = b; /* feed binary data into output */
1709                             chksum += b; /* calculate checksum */
1710                         }
1711                         highnibble ^= 1; /* toggle */
1712                     }
1713                     /* retrieve stored checksum value */
1714                     c = toupperW(*p++);
1715                     b = ( (c > '9') ? (c - 'A' + 10) : (c - '0') ) << 4;
1716                     c = toupperW(*p);
1717                     b +=  (c > '9') ? (c - 'A' + 10) : (c - '0');
1718                     if (b == (chksum & 0xff)) /* checksums match ? */
1719                         ret = TRUE;
1720                 }
1721             }
1722         }
1723     }
1724     RtlLeaveCriticalSection( &PROFILE_CritSect );
1725
1726     return ret;
1727 }
1728
1729 /***********************************************************************
1730  *           GetPrivateProfileStructA (KERNEL32.@)
1731  */
1732 BOOL WINAPI GetPrivateProfileStructA (LPCSTR section, LPCSTR key,
1733                                       LPVOID buffer, UINT len, LPCSTR filename)
1734 {
1735     UNICODE_STRING sectionW, keyW, filenameW;
1736     INT ret;
1737
1738     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1739     else sectionW.Buffer = NULL;
1740     if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1741     else keyW.Buffer = NULL;
1742     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1743     else filenameW.Buffer = NULL;
1744
1745     ret = GetPrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buffer, len,
1746                                    filenameW.Buffer);
1747     /* Do not translate binary data. */
1748
1749     RtlFreeUnicodeString(&sectionW);
1750     RtlFreeUnicodeString(&keyW);
1751     RtlFreeUnicodeString(&filenameW);
1752     return ret;
1753 }
1754
1755
1756
1757 /***********************************************************************
1758  *           WritePrivateProfileStructW (KERNEL32.@)
1759  */
1760 BOOL WINAPI WritePrivateProfileStructW (LPCWSTR section, LPCWSTR key,
1761                                         LPVOID buf, UINT bufsize, LPCWSTR filename)
1762 {
1763     BOOL ret = FALSE;
1764     LPBYTE binbuf;
1765     LPWSTR outstring, p;
1766     DWORD sum = 0;
1767
1768     if (!section && !key && !buf)  /* flush the cache */
1769         return WritePrivateProfileStringW( NULL, NULL, NULL, filename );
1770
1771     /* allocate string buffer for hex chars + checksum hex char + '\0' */
1772     outstring = HeapAlloc( GetProcessHeap(), 0, (bufsize*2 + 2 + 1) * sizeof(WCHAR) );
1773     p = outstring;
1774     for (binbuf = (LPBYTE)buf; binbuf < (LPBYTE)buf+bufsize; binbuf++) {
1775       *p++ = hex[*binbuf >> 4];
1776       *p++ = hex[*binbuf & 0xf];
1777       sum += *binbuf;
1778     }
1779     /* checksum is sum & 0xff */
1780     *p++ = hex[(sum & 0xf0) >> 4];
1781     *p++ = hex[sum & 0xf];
1782     *p++ = '\0';
1783
1784     RtlEnterCriticalSection( &PROFILE_CritSect );
1785
1786     if (PROFILE_Open( filename )) {
1787         ret = PROFILE_SetString( section, key, outstring, FALSE);
1788         PROFILE_FlushFile();
1789     }
1790
1791     RtlLeaveCriticalSection( &PROFILE_CritSect );
1792
1793     HeapFree( GetProcessHeap(), 0, outstring );
1794
1795     return ret;
1796 }
1797
1798 /***********************************************************************
1799  *           WritePrivateProfileStructA (KERNEL32.@)
1800  */
1801 BOOL WINAPI WritePrivateProfileStructA (LPCSTR section, LPCSTR key,
1802                                         LPVOID buf, UINT bufsize, LPCSTR filename)
1803 {
1804     UNICODE_STRING sectionW, keyW, filenameW;
1805     INT ret;
1806
1807     if (section) RtlCreateUnicodeStringFromAsciiz(&sectionW, section);
1808     else sectionW.Buffer = NULL;
1809     if (key) RtlCreateUnicodeStringFromAsciiz(&keyW, key);
1810     else keyW.Buffer = NULL;
1811     if (filename) RtlCreateUnicodeStringFromAsciiz(&filenameW, filename);
1812     else filenameW.Buffer = NULL;
1813
1814     /* Do not translate binary data. */
1815     ret = WritePrivateProfileStructW(sectionW.Buffer, keyW.Buffer, buf, bufsize,
1816                                      filenameW.Buffer);
1817
1818     RtlFreeUnicodeString(&sectionW);
1819     RtlFreeUnicodeString(&keyW);
1820     RtlFreeUnicodeString(&filenameW);
1821     return ret;
1822 }
1823
1824
1825 /***********************************************************************
1826  *           WriteOutProfiles   (KERNEL.315)
1827  */
1828 void WINAPI WriteOutProfiles16(void)
1829 {
1830     RtlEnterCriticalSection( &PROFILE_CritSect );
1831     PROFILE_FlushFile();
1832     RtlLeaveCriticalSection( &PROFILE_CritSect );
1833 }
1834
1835 /***********************************************************************
1836  *           CloseProfileUserMapping   (KERNEL32.@)
1837  */
1838 BOOL WINAPI CloseProfileUserMapping(void) {
1839     FIXME("(), stub!\n");
1840     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1841     return FALSE;
1842 }