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