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     PR_SetError(value, 0);
203     return;
204 }
205 
206 int
PORT_GetError(void)207 PORT_GetError(void)
208 {
209     return (PR_GetError());
210 }
211 
212 /********************* Arena code follows *****************************
213  * ArenaPools are like heaps.  The memory in them consists of large blocks,
214  * called arenas, which are allocated from the/a system heap.  Inside an
215  * ArenaPool, the arenas are organized as if they were in a stack.  Newly
216  * allocated arenas are "pushed" on that stack.  When you attempt to
217  * allocate memory from an ArenaPool, the code first looks to see if there
218  * is enough unused space in the top arena on the stack to satisfy your
219  * request, and if so, your request is satisfied from that arena.
220  * Otherwise, a new arena is allocated (or taken from NSPR's list of freed
221  * arenas) and pushed on to the stack.  The new arena is always big enough
222  * to satisfy the request, and is also at least a minimum size that is
223  * established at the time that the ArenaPool is created.
224  *
225  * The ArenaMark function returns the address of a marker in the arena at
226  * the top of the arena stack.  It is the address of the place in the arena
227  * on the top of the arena stack from which the next block of memory will
228  * be allocated.  Each ArenaPool has its own separate stack, and hence
229  * marks are only relevant to the ArenaPool from which they are gotten.
230  * Marks may be nested.  That is, a thread can get a mark, and then get
231  * another mark.
232  *
233  * It is intended that all the marks in an ArenaPool may only be owned by a
234  * single thread.  In DEBUG builds, this is enforced.  In non-DEBUG builds,
235  * it is not.  In DEBUG builds, when a thread gets a mark from an
236  * ArenaPool, no other thread may acquire a mark in that ArenaPool while
237  * that mark exists, that is, until that mark is unmarked or released.
238  * Therefore, it is important that every mark be unmarked or released when
239  * the creating thread has no further need for exclusive ownership of the
240  * right to manage the ArenaPool.
241  *
242  * The ArenaUnmark function discards the ArenaMark at the address given,
243  * and all marks nested inside that mark (that is, acquired from that same
244  * ArenaPool while that mark existed).   It is an error for a thread other
245  * than the mark's creator to try to unmark it.  When a thread has unmarked
246  * all its marks from an ArenaPool, then another thread is able to set
247  * marks in that ArenaPool.  ArenaUnmark does not deallocate (or "pop") any
248  * memory allocated from the ArenaPool since the mark was created.
249  *
250  * ArenaRelease "pops" the stack back to the mark, deallocating all the
251  * memory allocated from the arenas in the ArenaPool since that mark was
252  * created, and removing any arenas from the ArenaPool that have no
253  * remaining active allocations when that is done.  It implicitly releases
254  * any marks nested inside the mark being explicitly released.  It is the
255  * only operation, other than destroying the arenapool, that potentially
256  * reduces the number of arenas on the stack.  Otherwise, the stack grows
257  * until the arenapool is destroyed, at which point all the arenas are
258  * freed or returned to a "free arena list", depending on their sizes.
259  */
260 PLArenaPool *
PORT_NewArena(unsigned long chunksize)261 PORT_NewArena(unsigned long chunksize)
262 {
263     PORTArenaPool *pool;
264 
265     if (chunksize > MAX_SIZE) {
266         PORT_SetError(SEC_ERROR_NO_MEMORY);
267         return NULL;
268     }
269     pool = PORT_ZNew(PORTArenaPool);
270     if (!pool) {
271         return NULL;
272     }
273     pool->magic = ARENAPOOL_MAGIC;
274     pool->lock = PZ_NewLock(nssILockArena);
275     if (!pool->lock) {
276         PORT_Free(pool);
277         return NULL;
278     }
279     PL_InitArenaPool(&pool->arena, "security", chunksize, sizeof(double));
280     return (&pool->arena);
281 }
282 
283 void
PORT_InitCheapArena(PORTCheapArenaPool * pool,unsigned long chunksize)284 PORT_InitCheapArena(PORTCheapArenaPool *pool, unsigned long chunksize)
285 {
286     pool->magic = CHEAP_ARENAPOOL_MAGIC;
287     PL_InitArenaPool(&pool->arena, "security", chunksize, sizeof(double));
288 }
289 
290 void *
PORT_ArenaAlloc(PLArenaPool * arena,size_t size)291 PORT_ArenaAlloc(PLArenaPool *arena, size_t size)
292 {
293     void *p = NULL;
294 
295     PORTArenaPool *pool = (PORTArenaPool *)arena;
296 
297     if (size <= 0) {
298         size = 1;
299     }
300 
301     if (size > MAX_SIZE) {
302         /* you lose. */
303     } else
304         /* Is it one of ours?  Assume so and check the magic */
305         if (ARENAPOOL_MAGIC == pool->magic) {
306         PZ_Lock(pool->lock);
307 #ifdef THREADMARK
308         /* Most likely one of ours.  Is there a thread id? */
309         if (pool->marking_thread &&
310             pool->marking_thread != PR_GetCurrentThread()) {
311             /* Another thread holds a mark in this arena */
312             PZ_Unlock(pool->lock);
313             PORT_SetError(SEC_ERROR_NO_MEMORY);
314             PORT_Assert(0);
315             return NULL;
316         } /* tid != null */
317 #endif    /* THREADMARK */
318         PL_ARENA_ALLOCATE(p, arena, size);
319         PZ_Unlock(pool->lock);
320     } else {
321         PL_ARENA_ALLOCATE(p, arena, size);
322     }
323 
324     if (!p) {
325         PORT_SetError(SEC_ERROR_NO_MEMORY);
326     }
327 
328     return (p);
329 }
330 
331 void *
PORT_ArenaZAlloc(PLArenaPool * arena,size_t size)332 PORT_ArenaZAlloc(PLArenaPool *arena, size_t size)
333 {
334     void *p;
335 
336     if (size <= 0)
337         size = 1;
338 
339     p = PORT_ArenaAlloc(arena, size);
340 
341     if (p) {
342         PORT_Memset(p, 0, size);
343     }
344 
345     return (p);
346 }
347 
348 static PRCallOnceType setupUseFreeListOnce;
349 static PRBool useFreeList;
350 
351 static PRStatus
SetupUseFreeList(void)352 SetupUseFreeList(void)
353 {
354     useFreeList = (PR_GetEnvSecure("NSS_DISABLE_ARENA_FREE_LIST") == NULL);
355     return PR_SUCCESS;
356 }
357 
358 /*
359  * If zero is true, zeroize the arena memory before freeing it.
360  */
361 void
PORT_FreeArena(PLArenaPool * arena,PRBool zero)362 PORT_FreeArena(PLArenaPool *arena, PRBool zero)
363 {
364     PORTArenaPool *pool = (PORTArenaPool *)arena;
365     PRLock *lock = (PRLock *)0;
366     size_t len = sizeof *arena;
367 
368     if (!pool)
369         return;
370     if (ARENAPOOL_MAGIC == pool->magic) {
371         len = sizeof *pool;
372         lock = pool->lock;
373         PZ_Lock(lock);
374     }
375     if (zero) {
376         PL_ClearArenaPool(arena, 0);
377     }
378     (void)PR_CallOnce(&setupUseFreeListOnce, &SetupUseFreeList);
379     if (useFreeList) {
380         PL_FreeArenaPool(arena);
381     } else {
382         PL_FinishArenaPool(arena);
383     }
384     PORT_ZFree(arena, len);
385     if (lock) {
386         PZ_Unlock(lock);
387         PZ_DestroyLock(lock);
388     }
389 }
390 
391 void
PORT_DestroyCheapArena(PORTCheapArenaPool * pool)392 PORT_DestroyCheapArena(PORTCheapArenaPool *pool)
393 {
394     (void)PR_CallOnce(&setupUseFreeListOnce, &SetupUseFreeList);
395     if (useFreeList) {
396         PL_FreeArenaPool(&pool->arena);
397     } else {
398         PL_FinishArenaPool(&pool->arena);
399     }
400 }
401 
402 void *
PORT_ArenaGrow(PLArenaPool * arena,void * ptr,size_t oldsize,size_t newsize)403 PORT_ArenaGrow(PLArenaPool *arena, void *ptr, size_t oldsize, size_t newsize)
404 {
405     PORTArenaPool *pool = (PORTArenaPool *)arena;
406     PORT_Assert(newsize >= oldsize);
407 
408     if (newsize > MAX_SIZE) {
409         PORT_SetError(SEC_ERROR_NO_MEMORY);
410         return NULL;
411     }
412 
413     if (ARENAPOOL_MAGIC == pool->magic) {
414         PZ_Lock(pool->lock);
415         /* Do we do a THREADMARK check here? */
416         PL_ARENA_GROW(ptr, arena, oldsize, (newsize - oldsize));
417         PZ_Unlock(pool->lock);
418     } else {
419         PL_ARENA_GROW(ptr, arena, oldsize, (newsize - oldsize));
420     }
421 
422     return (ptr);
423 }
424 
425 void *
PORT_ArenaMark(PLArenaPool * arena)426 PORT_ArenaMark(PLArenaPool *arena)
427 {
428     void *result;
429 
430     PORTArenaPool *pool = (PORTArenaPool *)arena;
431     if (ARENAPOOL_MAGIC == pool->magic) {
432         PZ_Lock(pool->lock);
433 #ifdef THREADMARK
434         {
435             threadmark_mark *tm, **pw;
436             PRThread *currentThread = PR_GetCurrentThread();
437 
438             if (!pool->marking_thread) {
439                 /* First mark */
440                 pool->marking_thread = currentThread;
441             } else if (currentThread != pool->marking_thread) {
442                 PZ_Unlock(pool->lock);
443                 PORT_SetError(SEC_ERROR_NO_MEMORY);
444                 PORT_Assert(0);
445                 return NULL;
446             }
447 
448             result = PL_ARENA_MARK(arena);
449             PL_ARENA_ALLOCATE(tm, arena, sizeof(threadmark_mark));
450             if (!tm) {
451                 PZ_Unlock(pool->lock);
452                 PORT_SetError(SEC_ERROR_NO_MEMORY);
453                 return NULL;
454             }
455 
456             tm->mark = result;
457             tm->next = (threadmark_mark *)NULL;
458 
459             pw = &pool->first_mark;
460             while (*pw) {
461                 pw = &(*pw)->next;
462             }
463 
464             *pw = tm;
465         }
466 #else  /* THREADMARK */
467         result = PL_ARENA_MARK(arena);
468 #endif /* THREADMARK */
469         PZ_Unlock(pool->lock);
470     } else {
471         /* a "pure" NSPR arena */
472         result = PL_ARENA_MARK(arena);
473     }
474     return result;
475 }
476 
477 /*
478  * This function accesses the internals of PLArena, which is why it needs
479  * to use the NSPR internal macro PL_MAKE_MEM_UNDEFINED before the memset
480  * calls.
481  *
482  * We should move this function to NSPR as PL_ClearArenaAfterMark or add
483  * a PL_ARENA_CLEAR_AND_RELEASE macro.
484  *
485  * TODO: remove the #ifdef PL_MAKE_MEM_UNDEFINED tests when NSPR 4.10+ is
486  * widely available.
487  */
488 static void
port_ArenaZeroAfterMark(PLArenaPool * arena,void * mark)489 port_ArenaZeroAfterMark(PLArenaPool *arena, void *mark)
490 {
491     PLArena *a = arena->current;
492     if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
493 /* fast path: mark falls in the current arena */
494 #ifdef PL_MAKE_MEM_UNDEFINED
495         PL_MAKE_MEM_UNDEFINED(mark, a->avail - (PRUword)mark);
496 #endif
497         memset(mark, 0, a->avail - (PRUword)mark);
498     } else {
499         /* slow path: need to find the arena that mark falls in */
500         for (a = arena->first.next; a; a = a->next) {
501             PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
502             if (a->base <= (PRUword)mark && (PRUword)mark <= a->avail) {
503 #ifdef PL_MAKE_MEM_UNDEFINED
504                 PL_MAKE_MEM_UNDEFINED(mark, a->avail - (PRUword)mark);
505 #endif
506                 memset(mark, 0, a->avail - (PRUword)mark);
507                 a = a->next;
508                 break;
509             }
510         }
511         for (; a; a = a->next) {
512             PR_ASSERT(a->base <= a->avail && a->avail <= a->limit);
513 #ifdef PL_MAKE_MEM_UNDEFINED
514             PL_MAKE_MEM_UNDEFINED((void *)a->base, a->avail - a->base);
515 #endif
516             memset((void *)a->base, 0, a->avail - a->base);
517         }
518     }
519 }
520 
521 static void
port_ArenaRelease(PLArenaPool * arena,void * mark,PRBool zero)522 port_ArenaRelease(PLArenaPool *arena, void *mark, PRBool zero)
523 {
524     PORTArenaPool *pool = (PORTArenaPool *)arena;
525     if (ARENAPOOL_MAGIC == pool->magic) {
526         PZ_Lock(pool->lock);
527 #ifdef THREADMARK
528         {
529             threadmark_mark **pw;
530 
531             if (PR_GetCurrentThread() != pool->marking_thread) {
532                 PZ_Unlock(pool->lock);
533                 PORT_SetError(SEC_ERROR_NO_MEMORY);
534                 PORT_Assert(0);
535                 return /* no error indication available */;
536             }
537 
538             pw = &pool->first_mark;
539             while (*pw && (mark != (*pw)->mark)) {
540                 pw = &(*pw)->next;
541             }
542 
543             if (!*pw) {
544                 /* bad mark */
545                 PZ_Unlock(pool->lock);
546                 PORT_SetError(SEC_ERROR_NO_MEMORY);
547                 PORT_Assert(0);
548                 return /* no error indication available */;
549             }
550 
551             *pw = (threadmark_mark *)NULL;
552 
553             if (zero) {
554                 port_ArenaZeroAfterMark(arena, mark);
555             }
556             PL_ARENA_RELEASE(arena, mark);
557 
558             if (!pool->first_mark) {
559                 pool->marking_thread = (PRThread *)NULL;
560             }
561         }
562 #else  /* THREADMARK */
563         if (zero) {
564             port_ArenaZeroAfterMark(arena, mark);
565         }
566         PL_ARENA_RELEASE(arena, mark);
567 #endif /* THREADMARK */
568         PZ_Unlock(pool->lock);
569     } else {
570         if (zero) {
571             port_ArenaZeroAfterMark(arena, mark);
572         }
573         PL_ARENA_RELEASE(arena, mark);
574     }
575 }
576 
577 void
PORT_ArenaRelease(PLArenaPool * arena,void * mark)578 PORT_ArenaRelease(PLArenaPool *arena, void *mark)
579 {
580     port_ArenaRelease(arena, mark, PR_FALSE);
581 }
582 
583 /*
584  * Zeroize the arena memory before releasing it.
585  */
586 void
PORT_ArenaZRelease(PLArenaPool * arena,void * mark)587 PORT_ArenaZRelease(PLArenaPool *arena, void *mark)
588 {
589     port_ArenaRelease(arena, mark, PR_TRUE);
590 }
591 
592 void
PORT_ArenaUnmark(PLArenaPool * arena,void * mark)593 PORT_ArenaUnmark(PLArenaPool *arena, void *mark)
594 {
595 #ifdef THREADMARK
596     PORTArenaPool *pool = (PORTArenaPool *)arena;
597     if (ARENAPOOL_MAGIC == pool->magic) {
598         threadmark_mark **pw;
599 
600         PZ_Lock(pool->lock);
601 
602         if (PR_GetCurrentThread() != pool->marking_thread) {
603             PZ_Unlock(pool->lock);
604             PORT_SetError(SEC_ERROR_NO_MEMORY);
605             PORT_Assert(0);
606             return /* no error indication available */;
607         }
608 
609         pw = &pool->first_mark;
610         while (((threadmark_mark *)NULL != *pw) && (mark != (*pw)->mark)) {
611             pw = &(*pw)->next;
612         }
613 
614         if ((threadmark_mark *)NULL == *pw) {
615             /* bad mark */
616             PZ_Unlock(pool->lock);
617             PORT_SetError(SEC_ERROR_NO_MEMORY);
618             PORT_Assert(0);
619             return /* no error indication available */;
620         }
621 
622         *pw = (threadmark_mark *)NULL;
623 
624         if (!pool->first_mark) {
625             pool->marking_thread = (PRThread *)NULL;
626         }
627 
628         PZ_Unlock(pool->lock);
629     }
630 #endif /* THREADMARK */
631 }
632 
633 char *
PORT_ArenaStrdup(PLArenaPool * arena,const char * str)634 PORT_ArenaStrdup(PLArenaPool *arena, const char *str)
635 {
636     int len = PORT_Strlen(str) + 1;
637     char *newstr;
638 
639     newstr = (char *)PORT_ArenaAlloc(arena, len);
640     if (newstr) {
641         PORT_Memcpy(newstr, str, len);
642     }
643     return newstr;
644 }
645 
646 /********************** end of arena functions ***********************/
647 
648 /****************** unicode conversion functions ***********************/
649 /*
650  * NOTE: These conversion functions all assume that the multibyte
651  * characters are going to be in NETWORK BYTE ORDER, not host byte
652  * order.  This is because the only time we deal with UCS-2 and UCS-4
653  * are when the data was received from or is going to be sent out
654  * over the wire (in, e.g. certificates).
655  */
656 
657 void
PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc)658 PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
659 {
660     ucs4Utf8ConvertFunc = convFunc;
661 }
662 
663 void
PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc)664 PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc)
665 {
666     ucs2AsciiConvertFunc = convFunc;
667 }
668 
669 void
PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc)670 PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc)
671 {
672     ucs2Utf8ConvertFunc = convFunc;
673 }
674 
675 PRBool
PORT_UCS4_UTF8Conversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)676 PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
677                          unsigned int inBufLen, unsigned char *outBuf,
678                          unsigned int maxOutBufLen, unsigned int *outBufLen)
679 {
680     if (!ucs4Utf8ConvertFunc) {
681         return sec_port_ucs4_utf8_conversion_function(toUnicode,
682                                                       inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
683     }
684 
685     return (*ucs4Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
686                                   maxOutBufLen, outBufLen);
687 }
688 
689 PRBool
PORT_UCS2_UTF8Conversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)690 PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
691                          unsigned int inBufLen, unsigned char *outBuf,
692                          unsigned int maxOutBufLen, unsigned int *outBufLen)
693 {
694     if (!ucs2Utf8ConvertFunc) {
695         return sec_port_ucs2_utf8_conversion_function(toUnicode,
696                                                       inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen);
697     }
698 
699     return (*ucs2Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
700                                   maxOutBufLen, outBufLen);
701 }
702 
703 PRBool
PORT_ISO88591_UTF8Conversion(const unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen)704 PORT_ISO88591_UTF8Conversion(const unsigned char *inBuf,
705                              unsigned int inBufLen, unsigned char *outBuf,
706                              unsigned int maxOutBufLen, unsigned int *outBufLen)
707 {
708     return sec_port_iso88591_utf8_conversion_function(inBuf, inBufLen,
709                                                       outBuf, maxOutBufLen, outBufLen);
710 }
711 
712 PRBool
PORT_UCS2_ASCIIConversion(PRBool toUnicode,unsigned char * inBuf,unsigned int inBufLen,unsigned char * outBuf,unsigned int maxOutBufLen,unsigned int * outBufLen,PRBool swapBytes)713 PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf,
714                           unsigned int inBufLen, unsigned char *outBuf,
715                           unsigned int maxOutBufLen, unsigned int *outBufLen,
716                           PRBool swapBytes)
717 {
718     if (!ucs2AsciiConvertFunc) {
719         return PR_FALSE;
720     }
721 
722     return (*ucs2AsciiConvertFunc)(toUnicode, inBuf, inBufLen, outBuf,
723                                    maxOutBufLen, outBufLen, swapBytes);
724 }
725 
726 /* Portable putenv.  Creates/replaces an environment variable of the form
727  *  envVarName=envValue
728  */
729 int
NSS_PutEnv(const char * envVarName,const char * envValue)730 NSS_PutEnv(const char *envVarName, const char *envValue)
731 {
732     SECStatus result = SECSuccess;
733 #ifdef _WIN32
734     PRBool setOK;
735 
736     setOK = SetEnvironmentVariable(envVarName, envValue);
737     if (!setOK) {
738         SET_ERROR_CODE
739         return SECFailure;
740     }
741 #elif defined(__GNUC__) && __GNUC__ >= 7
742     int setEnvFailed;
743     setEnvFailed = setenv(envVarName, envValue, 1);
744     if (setEnvFailed) {
745         SET_ERROR_CODE
746         return SECFailure;
747     }
748 #else
749     char *encoded = (char *)PORT_ZAlloc(strlen(envVarName) + 2 + strlen(envValue));
750     if (!encoded) {
751         return SECFailure;
752     }
753     strcpy(encoded, envVarName);
754     strcat(encoded, "=");
755     strcat(encoded, envValue);
756     int putEnvFailed = putenv(encoded); /* adopt. */
757 
758     if (putEnvFailed) {
759         SET_ERROR_CODE
760         result = SECFailure;
761         PORT_Free(encoded);
762     }
763 #endif
764     return result;
765 }
766 
767 /*
768  * Perform a constant-time compare of two memory regions. The return value is
769  * 0 if the memory regions are equal and non-zero otherwise.
770  */
771 int
NSS_SecureMemcmp(const void * ia,const void * ib,size_t n)772 NSS_SecureMemcmp(const void *ia, const void *ib, size_t n)
773 {
774     const unsigned char *a = (const unsigned char *)ia;
775     const unsigned char *b = (const unsigned char *)ib;
776     size_t i;
777     unsigned char r = 0;
778 
779     for (i = 0; i < n; ++i) {
780         r |= *a++ ^ *b++;
781     }
782 
783     return r;
784 }
785 
786 /*
787  * Perform a constant-time check if a memory region is all 0. The return value
788  * is 0 if the memory region is all zero.
789  */
790 unsigned int
NSS_SecureMemcmpZero(const void * mem,size_t n)791 NSS_SecureMemcmpZero(const void *mem, size_t n)
792 {
793     PRUint8 zero = 0;
794     size_t i;
795     for (i = 0; i < n; ++i) {
796         zero |= *(PRUint8 *)((uintptr_t)mem + i);
797     }
798     return zero;
799 }
800