1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 /*
6  * secport.c - portability interfaces for security libraries
7  *
8  * This file abstracts out libc functionality that libsec depends on
9  *
10  * NOTE - These are not public interfaces
11  */
12 
13 #include "seccomon.h"
14 #include "prmem.h"
15 #include "prerror.h"
16 #include "plarena.h"
17 #include "secerr.h"
18 #include "prmon.h"
19 #include "nssilock.h"
20 #include "secport.h"
21 #include "prenv.h"
22 #include "prinit.h"
23 
24 #include <stdint.h>
25 
26 #ifdef DEBUG
27 #define THREADMARK
28 #endif /* DEBUG */
29 
30 #ifdef THREADMARK
31 #include "prthread.h"
32 #endif /* THREADMARK */
33 
34 #if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
35 #include <stdlib.h>
36 #else
37 #include "wtypes.h"
38 #endif
39 
40 #define SET_ERROR_CODE /* place holder for code to set PR error code. */
41 
42 #ifdef THREADMARK
43 typedef struct threadmark_mark_str {
44     struct threadmark_mark_str *next;
45     void *mark;
46 } threadmark_mark;
47 
48 #endif /* THREADMARK */
49 
50 /* The value of this magic must change each time PORTArenaPool changes. */
51 #define ARENAPOOL_MAGIC 0xB8AC9BDF
52 
53 #define CHEAP_ARENAPOOL_MAGIC 0x3F16BB09
54 
55 typedef struct PORTArenaPool_str {
56     PLArenaPool arena;
57     PRUint32 magic;
58     PRLock *lock;
59 #ifdef THREADMARK
60     PRThread *marking_thread;
61     threadmark_mark *first_mark;
62 #endif
63 } PORTArenaPool;
64 
65 /* locations for registering Unicode conversion functions.
66  * XXX is this the appropriate location?  or should they be
67  *     moved to client/server specific locations?
68  */
69 PORTCharConversionFunc ucs4Utf8ConvertFunc;
70 PORTCharConversionFunc ucs2Utf8ConvertFunc;
71 PORTCharConversionWSwapFunc ucs2AsciiConvertFunc;
72 
73 /* NSPR memory allocation functions (PR_Malloc, PR_Calloc, and PR_Realloc)
74  * use the PRUint32 type for the size parameter. Before we pass a size_t or
75  * unsigned long size to these functions, we need to ensure it is <= half of
76  * the maximum PRUint32 value to avoid truncation and catch a negative size.
77  */
78 #define MAX_SIZE (PR_UINT32_MAX >> 1)
79 
80 void *
PORT_Alloc(size_t bytes)81 PORT_Alloc(size_t bytes)
82 {
83     void *rv = NULL;
84 
85     if (bytes <= MAX_SIZE) {
86         /* Always allocate a non-zero amount of bytes */
87         rv = PR_Malloc(bytes ? bytes : 1);
88     }
89     if (!rv) {
90         PORT_SetError(SEC_ERROR_NO_MEMORY);
91     }
92     return rv;
93 }
94 
95 void *
PORT_Realloc(void * oldptr,size_t bytes)96 PORT_Realloc(void *oldptr, size_t bytes)
97 {
98     void *rv = NULL;
99 
100     if (bytes <= MAX_SIZE) {
101         rv = PR_Realloc(oldptr, bytes);
102     }
103     if (!rv) {
104         PORT_SetError(SEC_ERROR_NO_MEMORY);
105     }
106     return rv;
107 }
108 
109 void *
PORT_ZAlloc(size_t bytes)110 PORT_ZAlloc(size_t bytes)
111 {
112     void *rv = NULL;
113 
114     if (bytes <= MAX_SIZE) {
115         /* Always allocate a non-zero amount of bytes */
116         rv = PR_Calloc(1, bytes ? bytes : 1);
117     }
118     if (!rv) {
119         PORT_SetError(SEC_ERROR_NO_MEMORY);
120     }
121     return rv;
122 }
123 
124 /* aligned_alloc is C11. This is an alternative to get aligned memory. */
125 void *
PORT_ZAllocAligned(size_t bytes,size_t alignment,void ** mem)126 PORT_ZAllocAligned(size_t bytes, size_t alignment, void **mem)
127 {
128     size_t x = alignment - 1;
129 
130     /* This only works if alignment is a power of 2. */
131     if ((alignment == 0) || (alignment & (alignment - 1))) {
132         PORT_SetError(SEC_ERROR_INVALID_ARGS);
133         return NULL;
134     }
135 
136     if (!mem) {
137         return NULL;
138     }
139 
140     /* Always allocate a non-zero amount of bytes */
141     *mem = PORT_ZAlloc((bytes ? bytes : 1) + x);
142     if (!*mem) {
143         PORT_SetError(SEC_ERROR_NO_MEMORY);
144         return NULL;
145     }
146 
147     return (void *)(((uintptr_t)*mem + x) & ~(uintptr_t)x);
148 }
149 
150 void *
PORT_ZAllocAlignedOffset(size_t size,size_t alignment,size_t offset)151 PORT_ZAllocAlignedOffset(size_t size, size_t alignment, size_t offset)
152 {
153     PORT_Assert(offset < size);
154     if (offset > size) {
155         return NULL;
156     }
157 
158     void *mem = NULL;
159     void *v = PORT_ZAllocAligned(size, alignment, &mem);
160     if (!v) {
161         return NULL;
162     }
163 
164     PORT_Assert(mem);
165     *((void **)((uintptr_t)v + offset)) = mem;
166     return v;
167 }
168 
169 void
PORT_Free(void * ptr)170 PORT_Free(void *ptr)
171 {
172     if (ptr) {
173         PR_Free(ptr);
174     }
175 }
176 
177 void
PORT_ZFree(void * ptr,size_t len)178 PORT_ZFree(void *ptr, size_t len)
179 {
180     if (ptr) {
181         memset(ptr, 0, len);
182         PR_Free(ptr);
183     }
184 }
185 
186 char *
PORT_Strdup(const char * str)187 PORT_Strdup(const char *str)
188 {
189     size_t len = PORT_Strlen(str) + 1;
190     char *newstr;
191 
192     newstr = (char *)PORT_Alloc(len);
193     if (newstr) {
194         PORT_Memcpy(newstr, str, len);
195     }
196     return newstr;
197 }
198 
199 void
PORT_SetError(int value)200 PORT_SetError(int value)
201 {
202 #ifdef DEBUG_jp96085
203     PORT_Assert(value != SEC_ERROR_REUSED_ISSUER_AND_SERIAL);
204 #endif
205     PR_SetError(value, 0);
206     return;
207 }
208 
209 int
PORT_GetError(void)210 PORT_GetError(void)
211 {
212     return (PR_GetError());
213 }
214 
215 /********************* Arena code follows *****************************
216  * ArenaPools are like heaps.  The memory in them consists of large blocks,
217  * called arenas, which are allocated from the/a system heap.  Inside an
218  * ArenaPool, the arenas are organized as if they were in a stack.  Newly
219  * allocated arenas are "pushed" on that stack.  When you attempt to
220  * allocate memory from an ArenaPool, the code first looks to see if there
221  * is enough unused space in the top arena on the stack to satisfy your
222  * request, and if so, your request is satisfied from that arena.
223  * Otherwise, a new arena is allocated (or taken from NSPR's list of freed
224  * arenas) and pushed on to the stack.  The new arena is always big enough
225  * to satisfy the request, and is also at least a minimum size that is
226  * established at the time that the ArenaPool is created.
227  *
228  * The ArenaMark function returns the address of a marker in the arena at
229  * the top of the arena stack.  It is the address of the place in the arena
230  * on the top of the arena stack from which the next block of memory will
231  * be allocated.  Each ArenaPool has its own separate stack, and hence
232  * marks are only relevant to the ArenaPool from which they are gotten.
233  * Marks may be nested.  That is, a thread can get a mark, and then get
234  * another mark.
235  *
236  * It is intended that all the marks in an ArenaPool may only be owned by a
237  * single thread.  In DEBUG builds, this is enforced.  In non-DEBUG builds,
238  * it is not.  In DEBUG builds, when a thread gets a mark from an
239  * ArenaPool, no other thread may acquire a mark in that ArenaPool while
240  * that mark exists, that is, until that mark is unmarked or released.
241  * Therefore, it is important that every mark be unmarked or released when
242  * the creating thread has no further need for exclusive ownership of the
243  * right to manage the ArenaPool.
244  *
245  * The ArenaUnmark function discards the ArenaMark at the address given,
246  * and all marks nested inside that mark (that is, acquired from that same
247  * ArenaPool while that mark existed).   It is an error for a thread other
248  * than the mark's creator to try to unmark it.  When a thread has unmarked
249  * all its marks from an ArenaPool, then another thread is able to set
250  * marks in that ArenaPool.  ArenaUnmark does not deallocate (or "pop") any
251  * memory allocated from the ArenaPool since the mark was created.
252  *
253  * ArenaRelease "pops" the stack back to the mark, deallocating all the
254  * memory allocated from the arenas in the ArenaPool since that mark was
255  * created, and removing any arenas from the ArenaPool that have no
256  * remaining active allocations when that is done.  It implicitly releases
257  * any marks nested inside the mark being explicitly released.  It is the
258  * only operation, other than destroying the arenapool, that potentially
259  * reduces the number of arenas on the stack.  Otherwise, the stack grows
260  * until the arenapool is destroyed, at which point all the arenas are
261  * freed or returned to a "free arena list", depending on their sizes.
262  */
263 PLArenaPool *
PORT_NewArena(unsigned long chunksize)264 PORT_NewArena(unsigned long chunksize)
265 {
266     PORTArenaPool *pool;
267 
268     if (chunksize > MAX_SIZE) {
269         PORT_SetError(SEC_ERROR_NO_MEMORY);
270         return NULL;
271     }
272     pool = PORT_ZNew(PORTArenaPool);
273     if (!pool) {
274         return NULL;
275     }
276     pool->magic = ARENAPOOL_MAGIC;
277     pool->lock = PZ_NewLock(nssILockArena);
278     if (!pool->lock) {
279         PORT_Free(pool);
280         return NULL;
281     }
282     PL_InitArenaPool(&pool->arena, "security", chunksize, sizeof(double));
283     return (&pool->arena);
284 }
285 
286 void
PORT_InitCheapArena(PORTCheapArenaPool * pool,unsigned long chunksize)287 PORT_InitCheapArena(PORTCheapArenaPool *pool, unsigned long chunksize)
288 {
289     pool->magic = CHEAP_ARENAPOOL_MAGIC;
290     PL_InitArenaPool(&pool->arena, "security", chunksize, sizeof(double));
291 }
292 
293 void *
PORT_ArenaAlloc(PLArenaPool * arena,size_t size)294 PORT_ArenaAlloc(PLArenaPool *arena, size_t size)
295 {
296     void *p = NULL;
297 
298     PORTArenaPool *pool = (PORTArenaPool *)arena;
299 
300     if (size <= 0) {
301         size = 1;
302     }
303 
304     if (size > MAX_SIZE) {
305         /* you lose. */
306     } else
307         /* Is it one of ours?  Assume so and check the magic */
308         if (ARENAPOOL_MAGIC == pool->magic) {
309         PZ_Lock(pool->lock);
310 #ifdef THREADMARK
311         /* Most likely one of ours.  Is there a thread id? */
312         if (pool->marking_thread &&
313             pool->marking_thread != PR_GetCurrentThread()) {
314             /* Another thread holds a mark in this arena */
315             PZ_Unlock(pool->lock);
316             PORT_SetError(SEC_ERROR_NO_MEMORY);
317             PORT_Assert(0);
318             return NULL;
319         } /* tid != null */
320 #endif    /* THREADMARK */
321         PL_ARENA_ALLOCATE(p, arena, size);
322         PZ_Unlock(pool->lock);
323     } else {
324         PL_ARENA_ALLOCATE(p, arena, size);
325     }
326 
327     if (!p) {
328         PORT_SetError(SEC_ERROR_NO_MEMORY);
329     }
330 
331     return (p);
332 }
333 
334 void *
PORT_ArenaZAlloc(PLArenaPool * arena,size_t size)335 PORT_ArenaZAlloc(PLArenaPool *arena, size_t size)
336 {
337     void *p;
338 
339     if (size <= 0)
340         size = 1;
341 
342     p = PORT_ArenaAlloc(arena, size);
343 
344     if (p) {
345         PORT_Memset(p, 0, size);
346     }
347 
348     return (p);
349 }
350 
351 static PRCallOnceType setupUseFreeListOnce;
352 static PRBool useFreeList;
353 
354 static PRStatus
SetupUseFreeList(void)355 SetupUseFreeList(void)
356 {
357     useFreeList = (PR_GetEnvSecure("NSS_DISABLE_ARENA_FREE_LIST") == NULL);
358     return PR_SUCCESS;
359 }
360 
361 /*
362  * If zero is true, zeroize the arena memory before freeing it.
363  */
364 void
PORT_FreeArena(PLArenaPool * arena,PRBool zero)365 PORT_FreeArena(PLArenaPool *arena, PRBool zero)
366 {
367     PORTArenaPool *pool = (PORTArenaPool *)arena;
368     PRLock *lock = (PRLock *)0;
369     size_t len = sizeof *arena;
370 
371     if (!pool)
372         return;
373     if (ARENAPOOL_MAGIC == pool->magic) {
374         len = sizeof *pool;
375         lock = pool->lock;
376         PZ_Lock(lock);
377     }
378     if (zero) {
379         PL_ClearArenaPool(arena, 0);
380     }
381     (void)PR_CallOnce(&setupUseFreeListOnce, &SetupUseFreeList);
382     if (useFreeList) {
383         PL_FreeArenaPool(arena);
384     } else {
385         PL_FinishArenaPool(arena);
386     }
387     PORT_ZFree(arena, len);
388     if (lock) {
389         PZ_Unlock(lock);
390         PZ_DestroyLock(lock);
391     }
392 }
393 
394 void
PORT_DestroyCheapArena(PORTCheapArenaPool * pool)395 PORT_DestroyCheapArena(PORTCheapArenaPool *pool)
396 {
397     (void)PR_CallOnce(&setupUseFreeListOnce, &SetupUseFreeList);
398     if (useFreeList) {
399         PL_FreeArenaPool(&pool->arena);
400     } else {
401         PL_FinishArenaPool(&pool->arena);
402     }
403 }
404 
405 void *
PORT_ArenaGrow(PLArenaPool * arena,void * ptr,size_t oldsize,size_t newsize)406 PORT_ArenaGrow(PLArenaPool *arena, void *ptr, size_t oldsize, size_t newsize)
407 {
408     PORTArenaPool *pool = (PORTArenaPool *)arena;
409     PORT_Assert(newsize >= oldsize);
410 
411     if (newsize > MAX_SIZE) {
412         PORT_SetError(SEC_ERROR_NO_MEMORY);
413         return NULL;
414     }
415 
416     if (ARENAPOOL_MAGIC == pool->magic) {
417         PZ_Lock(pool->lock);
418         /* Do we do a THREADMARK check here? */
419         PL_ARENA_GROW(ptr, arena, oldsize, (newsize - oldsize));
420         PZ_Unlock(pool->lock);
421     } else {
422         PL_ARENA_GROW(ptr, arena, oldsize, (newsize - oldsize));
423     }
424 
425     return (ptr);
426 }
427 
428 void *
PORT_ArenaMark(PLArenaPool * arena)429 PORT_ArenaMark(PLArenaPool *arena)
430 {
431     void *result;
432 
433     PORTArenaPool *pool = (PORTArenaPool *)arena;
434     if (ARENAPOOL_MAGIC == pool->magic) {
435         PZ_Lock(pool->lock);
436 #ifdef THREADMARK
437         {
438             threadmark_mark *tm, **pw;
439             PRThread *currentThread = PR_GetCurrentThread();
440 
441             if (!pool->marking_thread) {
442                 /* First mark */
443                 pool->marking_thread = currentThread;
444             } else if (currentThread != pool->marking_thread) {
445                 PZ_Unlock(pool->lock);
446                 PORT_SetError(SEC_ERROR_NO_MEMORY);
447                 PORT_Assert(0);
448                 return NULL;
449             }
450 
451             result = PL_ARENA_MARK(arena);
452             PL_ARENA_ALLOCATE(tm, arena, sizeof(threadmark_mark));
453             if (!tm) {
454                 PZ_Unlock(pool->lock);
455                 PORT_SetError(SEC_ERROR_NO_MEMORY);
456                 return NULL;
457             }
458 
459             tm->mark = result;
460             tm->next = (threadmark_mark *)NULL;
461 
462             pw = &pool->first_mark;
463             while (*pw) {
464                 pw = &(*pw)->next;
465             }
466 
467             *pw = tm;
468         }
469 #else  /* THREADMARK */
470         result = PL_ARENA_MARK(arena);
471 #endif /* THREADMARK */
472         PZ_Unlock(pool->lock);
473     } else {
474         /* a "pure" NSPR arena */
475         result = PL_ARENA_MARK(arena);
476     }
477     return result;
478 }
479 
480 /*
481  * This function accesses the internals of PLArena, which is why it needs
482  * to use the NSPR internal macro PL_MAKE_MEM_UNDEFINED before the memset
483  * calls.
484  *
485  * We should move this function to NSPR as PL_ClearArenaAfterMark or add
486  * a PL_ARENA_CLEAR_AND_RELEASE macro.
487  *
488  * TODO: remove the #ifdef PL_MAKE_MEM_UNDEFINED tests when NSPR 4.10+ is
489  * widely available.
490  */
491 static void
port_ArenaZeroAfterMark(PLArenaPool * arena,void * mark)492 port_ArenaZeroAfterMark(PLArenaPool *arena, void *mark)
493 {
494     PLArena *a = arena->current;
495     if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
496 /* fast path: mark falls in the current arena */
497 #ifdef PL_MAKE_MEM_UNDEFINED
498         PL_MAKE_MEM_UNDEFINED(mark, a->avail - (PRUword)mark);
499 #endif
500         memset(mark, 0, a->avail - (PRUword)mark);
501     } else {
502         /* slow path: need to find the arena that mark falls in */
503         for (a = arena->first.next; a; a = a->next) {
504             PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
505             if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
506 #ifdef PL_MAKE_MEM_UNDEFINED
507                 PL_MAKE_MEM_UNDEFINED(mark, a->avail - (PRUword)mark);
508 #endif
509                 memset(mark, 0, a->avail - (PRUword)mark);
510                 a = a->next;
511                 break;
512             }
513         }
514         for (; a; a = a->next) {
515             PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
516 #ifdef PL_MAKE_MEM_UNDEFINED
517             PL_MAKE_MEM_UNDEFINED((void *)a->base, a->avail - a->base);
518 #endif
519             memset((void *)a->base, 0, a->avail - a->base);
520         }
521     }
522 }
523 
524 static void
port_ArenaRelease(PLArenaPool * arena,void * mark,PRBool zero)525 port_ArenaRelease(PLArenaPool *arena, void *mark, PRBool zero)
526 {
527     PORTArenaPool *pool = (PORTArenaPool *)arena;
528     if (ARENAPOOL_MAGIC == pool->magic) {
529         PZ_Lock(pool->lock);
530 #ifdef THREADMARK
531         {
532             threadmark_mark **pw;
533 
534             if (PR_GetCurrentThread() != pool->marking_thread) {
535                 PZ_Unlock(pool->lock);
536                 PORT_SetError(SEC_ERROR_NO_MEMORY);
537                 PORT_Assert(0);
538                 return /* no error indication available */;
539             }
540 
541             pw = &pool->first_mark;
542             while (*pw && (mark != (*pw)->mark)) {
543                 pw = &(*pw)->next;
544             }
545 
546             if (!*pw) {
547                 /* bad mark */
548                 PZ_Unlock(pool->lock);
549                 PORT_SetError(SEC_ERROR_NO_MEMORY);
550                 PORT_Assert(0);
551                 return /* no error indication available */;
552             }
553 
554             *pw = (threadmark_mark *)NULL;
555 
556             if (zero) {
557                 port_ArenaZeroAfterMark(arena, mark);
558             }
559             PL_ARENA_RELEASE(arena, mark);
560 
561             if (!pool->first_mark) {
562                 pool->marking_thread = (PRThread *)NULL;
563             }
564         }
565 #else  /* THREADMARK */
566         if (zero) {
567             port_ArenaZeroAfterMark(arena, mark);
568         }
569         PL_ARENA_RELEASE(arena, mark);
570 #endif /* THREADMARK */
571         PZ_Unlock(pool->lock);
572     } else {
573         if (zero) {
574             port_ArenaZeroAfterMark(arena, mark);
575         }
576         PL_ARENA_RELEASE(arena, mark);
577     }
578 }
579 
580 void
PORT_ArenaRelease(PLArenaPool * arena,void * mark)581 PORT_ArenaRelease(PLArenaPool *arena, void *mark)
582 {
583     port_ArenaRelease(arena, mark, PR_FALSE);
584 }
585 
586 /*
587  * Zeroize the arena memory before releasing it.
588  */
589 void
PORT_ArenaZRelease(PLArenaPool * arena,void * mark)590 PORT_ArenaZRelease(PLArenaPool *arena, void *mark)
591 {
592     port_ArenaRelease(arena, mark, PR_TRUE);
593 }
594 
595 void
PORT_ArenaUnmark(PLArenaPool * arena,void * mark)596 PORT_ArenaUnmark(PLArenaPool *arena, void *mark)
597 {
598 #ifdef THREADMARK
599     PORTArenaPool *pool = (PORTArenaPool *)arena;
600     if (ARENAPOOL_MAGIC == pool->magic) {
601         threadmark_mark **pw;
602 
603         PZ_Lock(pool->lock);
604 
605         if (PR_GetCurrentThread() != pool->marking_thread) {
606             PZ_Unlock(pool->lock);
607             PORT_SetError(SEC_ERROR_NO_MEMORY);
608             PORT_Assert(0);
609             return /* no error indication available */;
610         }
611 
612         pw = &pool->first_mark;
613         while (((threadmark_mark *)NULL != *pw) && (mark != (*pw)->mark)) {
614             pw = &(*pw)->next;
615         }
616 
617         if ((threadmark_mark *)NULL == *pw) {
618             /* bad mark */
619             PZ_Unlock(pool->lock);
620             PORT_SetError(SEC_ERROR_NO_MEMORY);
621             PORT_Assert(0);
622             return /* no error indication available */;
623         }
624 
625         *pw = (threadmark_mark *)NULL;
626 
627         if (!pool->first_mark) {
628             pool->marking_thread = (PRThread *)NULL;
629         }
630 
631         PZ_Unlock(pool->lock);
632     }
633 #endif /* THREADMARK */
634 }
635 
636 char *
PORT_ArenaStrdup(PLArenaPool * arena,const char * str)637 PORT_ArenaStrdup(PLArenaPool *arena, const char *str)
638 {
639     int len = PORT_Strlen(str) + 1;
640     char *newstr;
641 
642     newstr = (char *)PORT_ArenaAlloc(arena, len);
643     if (newstr) {
644         PORT_Memcpy(newstr, str, len);
645     }
646     return newstr;
647 }
648 
649 /********************** end of arena functions ***********************/
650 
651 /****************** unicode conversion functions ***********************/
652 /*
653  * NOTE: These conversion functions all assume that the multibyte
654  * characters are going to be in NETWORK BYTE ORDER, not host byte
655  * order.  This is because the only time we deal with UCS-2 and UCS-4
656  * are when the data was received from or is going to be sent out
657  * over the wire (in, e.g. certificates).
658  */
659 
660 void
PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc)661 PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
662 {
663     ucs4Utf8ConvertFunc = convFunc;
664 }
665 
666 void
PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc)667 PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc)
668 {
669     ucs2AsciiConvertFunc = convFunc;
670 }
671 
672 void
PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc)673 PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
674 {
675     ucs2Utf8ConvertFunc = convFunc;
676 }
677 
678 PRBool
PORT_UCS4_UTF8Conversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)679 PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
680                          unsigned int inBufLen, unsigned char *outBuf,
681                          unsigned int maxOutBufLen, unsigned int *outBufLen)
682 {
683     if (!ucs4Utf8ConvertFunc) {
684         return sec_port_ucs4_utf8_conversion_function(toUnicode,
685                                                       inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
686     }
687 
688     return (*ucs4Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
689                                   maxOutBufLen, outBufLen);
690 }
691 
692 PRBool
PORT_UCS2_UTF8Conversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)693 PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
694                          unsigned int inBufLen, unsigned char *outBuf,
695                          unsigned int maxOutBufLen, unsigned int *outBufLen)
696 {
697     if (!ucs2Utf8ConvertFunc) {
698         return sec_port_ucs2_utf8_conversion_function(toUnicode,
699                                                       inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
700     }
701 
702     return (*ucs2Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
703                                   maxOutBufLen, outBufLen);
704 }
705 
706 PRBool
PORT_ISO88591_UTF8Conversion(const unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)707 PORT_ISO88591_UTF8Conversion(const unsigned char *inBuf,
708                              unsigned int inBufLen, unsigned char *outBuf,
709                              unsigned int maxOutBufLen, unsigned int *outBufLen)
710 {
711     return sec_port_iso88591_utf8_conversion_function(inBuf, inBufLen,
712                                                       outBuf, maxOutBufLen, outBufLen);
713 }
714 
715 PRBool
PORT_UCS2_ASCIIConversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen,PRBool swapBytes)716 PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf,
717                           unsigned int inBufLen, unsigned char *outBuf,
718                           unsigned int maxOutBufLen, unsigned int *outBufLen,
719                           PRBool swapBytes)
720 {
721     if (!ucs2AsciiConvertFunc) {
722         return PR_FALSE;
723     }
724 
725     return (*ucs2AsciiConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
726                                    maxOutBufLen, outBufLen, swapBytes);
727 }
728 
729 /* Portable putenv.  Creates/replaces an environment variable of the form
730  *  envVarName=envValue
731  */
732 int
NSS_PutEnv(const char * envVarName,const char * envValue)733 NSS_PutEnv(const char *envVarName, const char *envValue)
734 {
735     SECStatus result = SECSuccess;
736     char *encoded;
737     int putEnvFailed;
738 #ifdef _WIN32
739     PRBool setOK;
740 
741     setOK = SetEnvironmentVariable(envVarName, envValue);
742     if (!setOK) {
743         SET_ERROR_CODE
744         return SECFailure;
745     }
746 #endif
747 
748     encoded = (char *)PORT_ZAlloc(strlen(envVarName) + 2 + strlen(envValue));
749     if (!encoded) {
750         return SECFailure;
751     }
752     strcpy(encoded, envVarName);
753     strcat(encoded, "=");
754     strcat(encoded, envValue);
755 
756     putEnvFailed = putenv(encoded); /* adopt. */
757     if (putEnvFailed) {
758         SET_ERROR_CODE
759         result = SECFailure;
760         PORT_Free(encoded);
761     }
762     return result;
763 }
764 
765 /*
766  * Perform a constant-time compare of two memory regions. The return value is
767  * 0 if the memory regions are equal and non-zero otherwise.
768  */
769 int
NSS_SecureMemcmp(const void * ia,const void * ib,size_t n)770 NSS_SecureMemcmp(const void *ia, const void *ib, size_t n)
771 {
772     const unsigned char *a = (const unsigned char *)ia;
773     const unsigned char *b = (const unsigned char *)ib;
774     size_t i;
775     unsigned char r = 0;
776 
777     for (i = 0; i < n; ++i) {
778         r |= *a++ ^ *b++;
779     }
780 
781     return r;
782 }
783 
784 /*
785  * Perform a constant-time check if a memory region is all 0. The return value
786  * is 0 if the memory region is all zero.
787  */
788 unsigned int
NSS_SecureMemcmpZero(const void * mem,size_t n)789 NSS_SecureMemcmpZero(const void *mem, size_t n)
790 {
791     PRUint8 zero = 0;
792     size_t i;
793     for (i = 0; i < n; ++i) {
794         zero |= *(PRUint8 *)((uintptr_t)mem + i);
795     }
796     return zero;
797 }
798