berval.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* See http://www.python-ldap.org/ for details.
  2. * $Id: berval.c,v 1.1 2009/08/17 01:49:47 leonard Exp $ */
  3. #include "common.h"
  4. #include "berval.h"
  5. /*
  6. * Converts a Python object into a data for a berval structure.
  7. *
  8. * New memory is allocated, and the content of the object is copied into it.
  9. * Then the (pre-existing) berval structure's field are filled in with pointer
  10. * and length data.
  11. *
  12. * The source object must implement the buffer interface, or be None.
  13. * If the source object is None, bv->bv_val will be set to NULL and bv_len to 0.
  14. * Otherwise, bv->bv_val will be non-NULL (even for zero-length data).
  15. * This allows the caller to distinguish a None argument as something special.
  16. *
  17. * Returns 0 on failure, leaving *bv unchanged, and setting an error.
  18. * Returns 1 on success: the berval must be freed with LDAPberval_release().
  19. */
  20. int
  21. LDAPberval_from_object(PyObject *obj, struct berval *bv)
  22. {
  23. const void *data;
  24. char *datacp;
  25. Py_ssize_t len;
  26. if (PyNone_Check(obj)) {
  27. bv->bv_len = 0;
  28. bv->bv_val = NULL;
  29. return 1;
  30. }
  31. if (!PyObject_AsReadBuffer(obj, &data, &len))
  32. return 0;
  33. datacp = PyMem_MALLOC(len ? len : 1);
  34. if (!datacp) {
  35. PyErr_NoMemory();
  36. return 0;
  37. }
  38. memcpy(datacp, data, len);
  39. bv->bv_len = len;
  40. bv->bv_val = datacp;
  41. return 1;
  42. }
  43. /*
  44. * Returns true if the object could be used to initialize a berval structure
  45. * with LDAPberval_from_object()
  46. */
  47. int
  48. LDAPberval_from_object_check(PyObject *obj)
  49. {
  50. return PyNone_Check(obj) ||
  51. PyObject_CheckReadBuffer(obj);
  52. }
  53. /*
  54. * Releases memory allocated by LDAPberval_from_object().
  55. * Has no effect if the berval pointer is NULL or the berval data is NULL.
  56. */
  57. void
  58. LDAPberval_release(struct berval *bv) {
  59. if (bv && bv->bv_val) {
  60. PyMem_FREE(bv->bv_val);
  61. bv->bv_len = 0;
  62. bv->bv_val = NULL;
  63. }
  64. }
  65. /*
  66. * Copies out the data from a berval, and returns it as a new Python object,
  67. * Returns None if the berval pointer is NULL.
  68. *
  69. * Note that this function is not the exact inverse of LDAPberval_from_object
  70. * with regards to the NULL/None conversion.
  71. *
  72. * Returns a new Python object on success, or NULL on failure.
  73. */
  74. PyObject *
  75. LDAPberval_to_object(const struct berval *bv)
  76. {
  77. PyObject *ret = NULL;
  78. if (!bv) {
  79. ret = Py_None;
  80. Py_INCREF(ret);
  81. }
  82. else {
  83. ret = PyString_FromStringAndSize(bv->bv_val, bv->bv_len);
  84. }
  85. return ret;
  86. }