strlcpy.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * ngIRCd -- The Next Generation IRC Daemon
  3. * Copyright (c)2001-2014 Alexander Barton (alex@barton.de) and Contributors.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. * Please read the file COPYING, README and AUTHORS for more information.
  10. */
  11. #include "portab.h"
  12. /**
  13. * @file
  14. * strlcpy() and strlcat() replacement functions.
  15. *
  16. * See <http://www.openbsd.org/papers/strlcpy-paper.ps> for details.
  17. *
  18. * Code partially borrowed from compat.c of rsync, written by Andrew
  19. * Tridgell (1998) and Martin Pool (2002):
  20. * <http://cvs.samba.org/cgi-bin/cvsweb/rsync/lib/compat.c>
  21. */
  22. #include <string.h>
  23. #include <sys/types.h>
  24. #ifndef HAVE_STRLCAT
  25. GLOBAL size_t
  26. strlcat( char *dst, const char *src, size_t size )
  27. {
  28. /* Like strncat() but does not 0 fill the buffer and
  29. * always null terminates. */
  30. size_t len1 = strlen( dst );
  31. size_t len2 = strlen( src );
  32. size_t ret = len1 + len2;
  33. if( size && ( len1 < size - 1 )) {
  34. if( len2 >= size - len1 )
  35. len2 = size - len1 - 1;
  36. memcpy( dst + len1, src, len2 );
  37. dst[len1 + len2] = 0;
  38. }
  39. return ret;
  40. } /* strlcat */
  41. #endif
  42. #ifndef HAVE_STRLCPY
  43. GLOBAL size_t
  44. strlcpy( char *dst, const char *src, size_t size )
  45. {
  46. /* Like strncpy but does not 0 fill the buffer and
  47. * always null terminates. */
  48. size_t len = strlen( src );
  49. size_t ret = len;
  50. if( size > 0 ) {
  51. if( len >= size ) len = size - 1;
  52. memcpy( dst, src, len );
  53. dst[len] = 0;
  54. }
  55. return ret;
  56. } /* strlcpy */
  57. #endif
  58. /* -eof- */