Debian Codegraph @

src/mime.c

raw
1 #include "pycurl.h"
2
3 #ifdef HAVE_CURL_MIME
4
5 /*
6 * Shared userdata passed to curl_mime_data_cb callbacks.
7 * One owner can be referenced by multiple duplicated easy handles.
8 */
9 typedef struct CurlMimeDataCbOwner {
10 PyObject_HEAD
11 PyObject *read_cb;
12 PyObject *seek_cb;
13 PyObject *free_cb;
14 PyObject *userdata;
15 Py_ssize_t shared_refcount;
16 int free_called;
17 } CurlMimeDataCbOwner;
18
19 static PyTypeObject CurlMimeDataCbOwner_Type;
20
21 static int
22 curlmime_check_state(CurlMimeObject *self, const char *name)
23 {
24 if (self->mime == NULL) {
25 PyErr_Format(ErrorObject, "cannot invoke %s() - no mime handle", name);
26 return -1;
27 }
28 if (self->curl == NULL) {
29 PyErr_Format(ErrorObject, "cannot invoke %s() - no curl handle", name);
30 return -1;
31 }
32 return check_curl_state(self->curl, 1 | 2, name);
33 }
34
35 static int
36 curlmimepart_check_state(CurlMimePartObject *self, const char *name)
37 {
38 CurlMimeObject *mime = self->mime;
39
40 if (mime == NULL || mime->mime == NULL) {
41 PyErr_Format(ErrorObject, "cannot invoke %s() - no mime handle", name);
42 return -1;
43 }
44 if (self->part == NULL) {
45 PyErr_Format(ErrorObject, "cannot invoke %s() - no mime part", name);
46 return -1;
47 }
48 if (mime->curl == NULL) {
49 PyErr_Format(ErrorObject, "cannot invoke %s() - no curl handle", name);
50 return -1;
51 }
52 return check_curl_state(mime->curl, 1 | 2, name);
53 }
54
55 static void
56 curlmime_set_error(CurlObject *curl, int code)
57 {
58 if (curl != NULL) {
59 create_and_set_error_object(curl, code);
60 return;
61 }
62
63 {
64 PyObject *v = Py_BuildValue("(is)", code, curl_easy_strerror((CURLcode)code));
65 if (v != NULL) {
66 PyErr_SetObject(ErrorObject, v);
67 Py_DECREF(v);
68 }
69 }
70 }
71
72 static int
73 curlmime_data_cb_owner_traverse(CurlMimeDataCbOwner *self, visitproc visit, void *arg)
74 {
75 int err;
76 #undef VISIT
77 #define VISIT(v) if ((v) != NULL && ((err = visit(v, arg)) != 0)) return err
78
79 VISIT(self->read_cb);
80 VISIT(self->seek_cb);
81 VISIT(self->free_cb);
82 VISIT(self->userdata);
83
84 return 0;
85 #undef VISIT
86 }
87
88 static int
89 curlmime_data_cb_owner_clear(CurlMimeDataCbOwner *self)
90 {
91 Py_CLEAR(self->read_cb);
92 Py_CLEAR(self->seek_cb);
93 Py_CLEAR(self->free_cb);
94 Py_CLEAR(self->userdata);
95 return 0;
96 }
97
98 static void
99 curlmime_data_cb_owner_dealloc(CurlMimeDataCbOwner *self)
100 {
101 PyObject_GC_UnTrack(self);
102 Py_TRASHCAN_BEGIN(self, curlmime_data_cb_owner_dealloc);
103 curlmime_data_cb_owner_clear(self);
104 Py_TYPE(self)->tp_free((PyObject *)self);
105 Py_TRASHCAN_END;
106 }
107
108 static CurlMimeDataCbOwner *
109 curlmime_data_cb_owner_new(PyObject *read_cb, PyObject *seek_cb, PyObject *free_cb, PyObject *userdata)
110 {
111 CurlMimeDataCbOwner *owner;
112
113 if (!(CurlMimeDataCbOwner_Type.tp_flags & Py_TPFLAGS_READY)) {
114 if (PyType_Ready(&CurlMimeDataCbOwner_Type) != 0) {
115 return NULL;
116 }
117 }
118
119 owner = (CurlMimeDataCbOwner *)CurlMimeDataCbOwner_Type.tp_alloc(
120 &CurlMimeDataCbOwner_Type, 0
121 );
122 if (owner == NULL) {
123 return NULL;
124 }
125
126 owner->read_cb = NULL;
127 owner->seek_cb = NULL;
128 owner->free_cb = NULL;
129 owner->userdata = NULL;
130 owner->shared_refcount = 0;
131 owner->free_called = 0;
132
133 Py_INCREF(read_cb);
134 owner->read_cb = read_cb;
135
136 if (seek_cb != Py_None) {
137 Py_INCREF(seek_cb);
138 owner->seek_cb = seek_cb;
139 }
140 if (free_cb != Py_None) {
141 Py_INCREF(free_cb);
142 owner->free_cb = free_cb;
143 }
144 Py_INCREF(userdata);
145 owner->userdata = userdata;
146
147 return owner;
148 }
149
150 static void
151 curlmime_data_cb_owner_add_libcurl_ref(CurlMimeDataCbOwner *owner)
152 {
153 if (owner == NULL) {
154 return;
155 }
156
157 /*
158 * Track one logical reference per easy handle that may invoke libcurl's
159 * freefunc for this owner.
160 */
161 owner->shared_refcount += 1;
162 Py_INCREF(owner);
163 }
164
165 static void
166 curlmime_data_cb_owner_release_libcurl_ref(CurlMimeDataCbOwner *owner, int invoke_user_free)
167 {
168 PyObject *free_result = NULL;
169
170 if (owner == NULL) {
171 return;
172 }
173
174 if (owner->shared_refcount <= 0) {
175 /*
176 * Defensive: do not decref without a matching logical libcurl ref.
177 * This avoids crashing on unexpected extra freefunc invocations.
178 */
179 PyErr_SetString(ErrorObject, "internal error: mime data_cb owner libcurl refcount underflow");
180 PyErr_WriteUnraisable((PyObject *)owner);
181 return;
182 }
183 owner->shared_refcount -= 1;
184
185 if (invoke_user_free && owner->shared_refcount == 0 && !owner->free_called) {
186 owner->free_called = 1;
187
188 if (owner->free_cb != NULL) {
189 free_result = PyObject_CallFunctionObjArgs(owner->free_cb, owner->userdata, NULL);
190 if (free_result == NULL) {
191 PyErr_WriteUnraisable(owner->free_cb);
192 } else {
193 Py_DECREF(free_result);
194 }
195 }
196 }
197
198 Py_DECREF(owner);
199 }
200
201 static int
202 curlmime_owner_list_remove_ptr(PyObject *owners, PyObject *owner_obj)
203 {
204 Py_ssize_t i;
205 Py_ssize_t len;
206
207 if (owners == NULL || owner_obj == NULL) {
208 return 0;
209 }
210 if (!PyList_Check(owners)) {
211 PyErr_SetString(ErrorObject, "internal error: owner list is not a list");
212 return -1;
213 }
214
215 assert(PyList_Check(owners));
216 len = PyList_GET_SIZE(owners);
217 for (i = 0; i < len; i++) {
218 if (PyList_GET_ITEM(owners, i) == owner_obj) {
219 if (PySequence_DelItem(owners, i) != 0) {
220 return -1;
221 }
222 break;
223 }
224 }
225 return 0;
226 }
227
228 static int
229 curlmimepart_drop_data_cb_owner(CurlMimePartObject *self)
230 {
231 PyObject *owners;
232
233 if (self->data_cb_owner == NULL) {
234 return 0;
235 }
236
237 owners = (self->mime != NULL) ? self->mime->data_cb_owners : NULL;
238 if (owners != NULL &&
239 curlmime_owner_list_remove_ptr(owners, self->data_cb_owner) != 0)
240 {
241 PyErr_Clear();
242 }
243
244 Py_CLEAR(self->data_cb_owner);
245 return 0;
246 }
247
248 static size_t
249 curlmimepart_read_callback(char *ptr, size_t size, size_t nmemb, void *arg)
250 {
251 CurlMimeDataCbOwner *owner = (CurlMimeDataCbOwner *)arg;
252 PyObject *arglist = NULL;
253 PyObject *result = NULL;
254 Py_buffer view;
255 size_t ret = CURL_READFUNC_ABORT;
256 int total_size;
257 PyGILState_STATE gil_state;
258
259 if (owner == NULL || owner->read_cb == NULL) {
260 return ret;
261 }
262 if (!Py_IsInitialized()) {
263 return ret;
264 }
265
266 /*
267 * Use GIL-state API instead of callback thread-state helpers because
268 * mime data callbacks can run for duplicated easy handles and are not
269 * tied to a single CurlObject callback state owner.
270 */
271 gil_state = PyGILState_Ensure();
272
273 if (size <= 0 || nmemb <= 0) {
274 goto done;
275 }
276 total_size = (int)(size * nmemb);
277 if (total_size < 0 || (size_t)total_size / size != nmemb) {
278 PyErr_SetString(ErrorObject, "integer overflow in mime read callback");
279 goto verbose_error;
280 }
281
282 arglist = Py_BuildValue("(Oi)", owner->userdata, total_size);
283 if (arglist == NULL) {
284 goto verbose_error;
285 }
286 result = PyObject_Call(owner->read_cb, arglist, NULL);
287 Py_DECREF(arglist);
288 arglist = NULL;
289 if (result == NULL) {
290 goto verbose_error;
291 }
292
293 if (PyObject_CheckBuffer(result)) {
294 if (PyObject_GetBuffer(result, &view, PyBUF_SIMPLE) != 0) {
295 goto verbose_error;
296 }
297 if (view.len < 0 || view.len > total_size) {
298 PyErr_Format(ErrorObject, "invalid return value for mime read callback (%ld bytes returned when at most %ld bytes were wanted)", (long)view.len, (long)total_size);
299 PyBuffer_Release(&view);
300 goto verbose_error;
301 }
302 memcpy(ptr, view.buf, (size_t)view.len);
303 ret = (size_t)view.len;
304 PyBuffer_Release(&view);
305 }
306 else if (PyUnicode_Check(result)) {
307 char *buf = NULL;
308 Py_ssize_t obj_size = -1;
309 Py_ssize_t conv_res;
310 PyObject *encoded = PyUnicode_AsEncodedString(result, "ascii", "strict");
311
312 if (encoded == NULL) {
313 goto verbose_error;
314 }
315 conv_res = PyBytes_AsStringAndSize(encoded, &buf, &obj_size);
316 if (conv_res != 0 || obj_size < 0 || obj_size > total_size) {
317 Py_DECREF(encoded);
318 PyErr_Format(ErrorObject, "invalid return value for mime read callback (%ld bytes returned after ASCII encoding when at most %ld bytes were wanted)", (long)obj_size, (long)total_size);
319 goto verbose_error;
320 }
321 memcpy(ptr, buf, obj_size);
322 Py_DECREF(encoded);
323 ret = (size_t)obj_size;
324 }
325 else if (PyLong_Check(result)) {
326 long long_res = PyLong_AsLong(result);
327 if (long_res != CURL_READFUNC_ABORT && long_res != CURL_READFUNC_PAUSE) {
328 PyErr_SetString(ErrorObject, "mime read callback must return a buffer object, an ASCII-only Unicode string, READFUNC_ABORT, or READFUNC_PAUSE");
329 goto verbose_error;
330 }
331 ret = (size_t)long_res;
332 }
333 else {
334 PyErr_SetString(ErrorObject, "mime read callback must return an object supporting the buffer protocol, an ASCII-only Unicode string, READFUNC_ABORT, or READFUNC_PAUSE");
335 goto verbose_error;
336 }
337
338 done:
339 Py_XDECREF(result);
340 PyGILState_Release(gil_state);
341 return ret;
342
343 verbose_error:
344 print_callback_error_if_regular_exception();
345 goto done;
346 }
347
348 static int
349 curlmimepart_seek_callback(void *arg, curl_off_t offset, int origin)
350 {
351 CurlMimeDataCbOwner *owner = (CurlMimeDataCbOwner *)arg;
352 PyObject *arglist = NULL;
353 PyObject *result = NULL;
354 int ret = CURL_SEEKFUNC_FAIL; /* Fail by default; user callback can return CANTSEEK explicitly. */
355 int source = 0;
356 PyGILState_STATE gil_state;
357
358 if (owner == NULL || owner->seek_cb == NULL) {
359 return ret;
360 }
361 if (!Py_IsInitialized()) {
362 return ret;
363 }
364
365 /*
366 * Use GIL-state API instead of callback thread-state helpers because
367 * mime data callbacks can run for duplicated easy handles and are not
368 * tied to a single CurlObject callback state owner.
369 */
370 gil_state = PyGILState_Ensure();
371
372 /* Match existing SEEKFUNCTION callback behavior: pass origin as 0/1/2. */
373 switch (origin)
374 {
375 case SEEK_SET:
376 source = 0;
377 break;
378 case SEEK_CUR:
379 source = 1;
380 break;
381 case SEEK_END:
382 source = 2;
383 break;
384 default:
385 source = origin;
386 break;
387 }
388
389 arglist = Py_BuildValue("(OLi)", owner->userdata, (PY_LONG_LONG)offset, source);
390 if (arglist == NULL) {
391 goto verbose_error;
392 }
393 result = PyObject_Call(owner->seek_cb, arglist, NULL);
394 Py_DECREF(arglist);
395 arglist = NULL;
396 if (result == NULL) {
397 goto verbose_error;
398 }
399
400 if (result == Py_None) {
401 ret = CURL_SEEKFUNC_OK;
402 }
403 else if (PyLong_Check(result)) {
404 int ret_code = (int)PyLong_AsLong(result);
405 if (PyErr_Occurred()) {
406 goto verbose_error;
407 }
408 if (ret_code < CURL_SEEKFUNC_OK || ret_code > CURL_SEEKFUNC_CANTSEEK) {
409 PyErr_Format(ErrorObject, "invalid return value for mime seek callback %d not in (0, 1, 2)", ret_code);
410 goto verbose_error;
411 }
412 ret = ret_code;
413 }
414 else {
415 PyErr_SetString(ErrorObject, "mime seek callback must return 0 (SEEKFUNC_OK), 1 (SEEKFUNC_FAIL), 2 (SEEKFUNC_CANTSEEK) or None");
416 goto verbose_error;
417 }
418
419 done:
420 Py_XDECREF(result);
421 PyGILState_Release(gil_state);
422 return ret;
423
424 verbose_error:
425 print_callback_error_if_regular_exception();
426 goto done;
427 }
428
429 static void
430 curlmimepart_free_callback(void *arg)
431 {
432 CurlMimeDataCbOwner *owner = (CurlMimeDataCbOwner *)arg;
433 PyGILState_STATE gil_state;
434
435 if (owner == NULL || !Py_IsInitialized()) {
436 return;
437 }
438
439 /*
440 * libcurl may invoke freefunc from non-Python threads, and duplicated easy
441 * handles can invoke it multiple times for the same owner pointer.
442 */
443 gil_state = PyGILState_Ensure();
444 curlmime_data_cb_owner_release_libcurl_ref(owner, 1);
445 PyGILState_Release(gil_state);
446 }
447
448 static int
449 curlmime_detach_if_pinned(CurlMimeObject *self, int report_error)
450 {
451 int res;
452
453 if (self == NULL || self->curl == NULL ||
454 self->curl->mimepost_obj != (PyObject *)self)
455 {
456 return 0;
457 }
458
459 if (self->curl->handle != NULL) {
460 res = (int)curl_easy_setopt(self->curl->handle, CURLOPT_MIMEPOST, NULL);
461 if (res != CURLE_OK) {
462 if (report_error) {
463 curlmime_set_error(self->curl, res);
464 }
465 return -1;
466 }
467 }
468
469 Py_CLEAR(self->curl->mimepost_obj);
470 return 0;
471 }
472
473 static struct curl_slist *
474 curlmime_headers_to_slist(PyObject *obj)
475 {
476 struct curl_slist *slist = NULL;
477 Py_ssize_t i;
478 int which;
479 Py_ssize_t len;
480
481 if (obj == Py_None) {
482 return NULL;
483 }
484
485 which = PyListOrTuple_Check(obj);
486 if (!which) {
487 PyErr_SetString(PyExc_TypeError, "headers must be a list or tuple of strings");
488 return NULL;
489 }
490
491 len = PyListOrTuple_Size(obj, which);
492 for (i = 0; i < len; i++) {
493 PyObject *header_obj = PyListOrTuple_GetItem(obj, i, which);
494 struct curl_slist *next;
495 char *header;
496 PyObject *encoded_obj = NULL;
497
498 if (!PyText_Check(header_obj)) {
499 curl_slist_free_all(slist);
500 PyErr_SetString(PyExc_TypeError, "headers must contain only byte or ascii-unicode strings");
501 return NULL;
502 }
503
504 header = PyText_AsString_NoNUL(header_obj, &encoded_obj);
505 if (header == NULL) {
506 curl_slist_free_all(slist);
507 return NULL;
508 }
509
510 next = curl_slist_append(slist, header);
511 Py_XDECREF(encoded_obj);
512 if (next == NULL) {
513 curl_slist_free_all(slist);
514 PyErr_NoMemory();
515 return NULL;
516 }
517 slist = next;
518 }
519
520 return slist;
521 }
522
523 static PyObject *
524 curlmime_make_part(CurlMimeObject *mime, curl_mimepart *part)
525 {
526 CurlMimePartObject *part_obj;
527
528 part_obj = (CurlMimePartObject *)p_CurlMimePart_Type->tp_alloc(p_CurlMimePart_Type, 0);
529 if (part_obj == NULL) {
530 return NULL;
531 }
532
533 part_obj->part = part;
534 part_obj->mime = (CurlMimeObject *)Py_NewRef((PyObject *)mime);
535 part_obj->data_cb_owner = NULL;
536
537 return (PyObject *)part_obj;
538 }
539
540 static int
541 curlmime_invalidate_parts(CurlMimeObject *self)
542 {
543 Py_ssize_t i;
544 Py_ssize_t len;
545
546 if (self->parts == NULL) {
547 return 0;
548 }
549
550 len = PyList_GET_SIZE(self->parts);
551 for (i = 0; i < len; i++) {
552 PyObject *part_obj = PyList_GET_ITEM(self->parts, i);
553 if (PyObject_TypeCheck(part_obj, p_CurlMimePart_Type)) {
554 CurlMimePartObject *part = (CurlMimePartObject *)part_obj;
555 if (part->mime == self) {
556 part->part = NULL;
557 Py_CLEAR(part->mime);
558 }
559 Py_CLEAR(part->data_cb_owner);
560 }
561 }
562
563 return 0;
564 }
565
566 static void
567 curlmime_invalidate_wrappers(CurlMimeObject *self)
568 {
569 Py_ssize_t i;
570 Py_ssize_t len;
571
572 if (self == NULL) {
573 return;
574 }
575
576 if (self->mime == NULL && self->curl == NULL &&
577 self->parts == NULL && self->submimes == NULL &&
578 self->data_cb_owners == NULL)
579 {
580 return;
581 }
582
583 /* Mark this wrapper as invalid first to avoid recursive cycles. */
584 self->mime = NULL;
585 self->owns_mime = 0;
586
587 (void)curlmime_invalidate_parts(self);
588
589 if (self->submimes != NULL) {
590 len = PyList_GET_SIZE(self->submimes);
591 for (i = 0; i < len; i++) {
592 PyObject *submime_obj = PyList_GET_ITEM(self->submimes, i);
593 if (PyObject_TypeCheck(submime_obj, p_CurlMime_Type)) {
594 curlmime_invalidate_wrappers((CurlMimeObject *)submime_obj);
595 }
596 }
597 }
598
599 Py_CLEAR(self->parts);
600 Py_CLEAR(self->submimes);
601 Py_CLEAR(self->data_cb_owners);
602 Py_CLEAR(self->curl);
603 }
604
605 static PyObject *
606 do_curlmime_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
607 {
608 CurlMimeObject *self;
609 CurlObject *curl;
610 static char *kwlist[] = {"curl", NULL};
611
612 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!", kwlist, p_Curl_Type, &curl)) {
613 return NULL;
614 }
615 if (check_curl_state(curl, 1 | 2, "CurlMime") != 0) {
616 return NULL;
617 }
618
619 self = (CurlMimeObject *)subtype->tp_alloc(subtype, 0);
620 if (self == NULL) {
621 return NULL;
622 }
623
624 self->owns_mime = 1;
625 self->curl = (CurlObject *)Py_NewRef((PyObject *)curl);
626 self->parts = PyList_New((Py_ssize_t)0);
627 if (self->parts == NULL) {
628 Py_DECREF(self);
629 return NULL;
630 }
631 self->submimes = PyList_New((Py_ssize_t)0);
632 if (self->submimes == NULL) {
633 Py_DECREF(self);
634 return NULL;
635 }
636 self->data_cb_owners = PyList_New((Py_ssize_t)0);
637 if (self->data_cb_owners == NULL) {
638 Py_DECREF(self);
639 return NULL;
640 }
641
642 self->mime = curl_mime_init(curl->handle);
643 if (self->mime == NULL) {
644 Py_DECREF(self);
645 PyErr_NoMemory();
646 return NULL;
647 }
648
649 return (PyObject *)self;
650 }
651
652 static int
653 do_curlmime_traverse(CurlMimeObject *self, visitproc visit, void *arg)
654 {
655 int err;
656 #undef VISIT
657 #define VISIT(v) if ((v) != NULL && ((err = visit(v, arg)) != 0)) return err
658
659 VISIT((PyObject *)self->curl);
660 VISIT(self->parts);
661 VISIT(self->submimes);
662 VISIT(self->data_cb_owners);
663
664 return 0;
665 #undef VISIT
666 }
667
668 static int
669 do_curlmime_clear(CurlMimeObject *self)
670 {
671 curl_mime *mime = self->mime;
672 int owns_mime = self->owns_mime;
673
674 if (curlmime_detach_if_pinned(self, 0) != 0) {
675 PyErr_Clear();
676 return 0;
677 }
678
679 curlmime_invalidate_wrappers(self);
680
681 if (owns_mime && mime != NULL) {
682 curl_mime_free(mime);
683 }
684 return 0;
685 }
686
687 static void
688 do_curlmime_dealloc(CurlMimeObject *self)
689 {
690 PyObject_GC_UnTrack(self);
691 Py_TRASHCAN_BEGIN(self, do_curlmime_dealloc);
692 do_curlmime_clear(self);
693 CurlMime_Type.tp_free(self);
694 Py_TRASHCAN_END;
695 }
696
697 static PyObject *
698 do_curlmime_close(CurlMimeObject *self, PyObject *Py_UNUSED(ignored))
699 {
700 if (self->curl != NULL && check_curl_state(self->curl, 2, "close") != 0) {
701 return NULL;
702 }
703 if (curlmime_detach_if_pinned(self, 1) != 0) {
704 return NULL;
705 }
706
707 do_curlmime_clear(self);
708 Py_RETURN_NONE;
709 }
710
711 static PyObject *
712 do_curlmime_closed(CurlMimeObject *self, PyObject *Py_UNUSED(ignored))
713 {
714 if (self->mime == NULL) {
715 Py_RETURN_TRUE;
716 } else {
717 Py_RETURN_FALSE;
718 }
719 }
720
721 static PyObject *
722 do_curlmime_addpart(CurlMimeObject *self, PyObject *Py_UNUSED(ignored))
723 {
724 curl_mimepart *part;
725 PyObject *part_obj;
726
727 if (curlmime_check_state(self, "addpart") != 0) {
728 return NULL;
729 }
730
731 part = curl_mime_addpart(self->mime);
732 if (part == NULL) {
733 PyErr_NoMemory();
734 return NULL;
735 }
736
737 part_obj = curlmime_make_part(self, part);
738 if (part_obj == NULL) {
739 return NULL;
740 }
741
742 if (PyList_Append(self->parts, part_obj) != 0) {
743 Py_DECREF(part_obj);
744 return NULL;
745 }
746
747 return part_obj;
748 }
749
750 static PyObject *
751 do_curlmime_enter(CurlMimeObject *self, PyObject *Py_UNUSED(ignored))
752 {
753 if (curlmime_check_state(self, "__enter__") != 0) {
754 return NULL;
755 }
756
757 Py_INCREF(self);
758 return (PyObject *)self;
759 }
760
761 static PyObject *
762 do_curlmime_exit(CurlMimeObject *self, PyObject *args)
763 {
764 PyObject *exc_type;
765 PyObject *exc;
766 PyObject *tb;
767
768 if (!PyArg_ParseTuple(args, "OOO:__exit__", &exc_type, &exc, &tb)) {
769 return NULL;
770 }
771
772 return do_curlmime_close(self, NULL);
773 }
774
775 static PyObject *do_curlmimepart_name(CurlMimePartObject *self, PyObject *arg);
776 static PyObject *do_curlmimepart_data(CurlMimePartObject *self, PyObject *arg);
777 static PyObject *do_curlmimepart_filedata(CurlMimePartObject *self, PyObject *arg);
778 static PyObject *do_curlmimepart_filename(CurlMimePartObject *self, PyObject *arg);
779 static PyObject *do_curlmimepart_type(CurlMimePartObject *self, PyObject *arg);
780 static PyObject *do_curlmimepart_encoder(CurlMimePartObject *self, PyObject *arg);
781 static PyObject *do_curlmimepart_data_cb(CurlMimePartObject *self, PyObject *args, PyObject *kwds);
782 static PyObject *do_curlmimepart_headers(CurlMimePartObject *self, PyObject *arg);
783 static PyObject *do_curlmimepart_subparts(CurlMimePartObject *self, PyObject *arg);
784
785 static int
786 curlmimepart_data_as_string_or_buffer(PyObject *arg,
787 char **data,
788 Py_ssize_t *data_len,
789 PyObject **encoded_obj,
790 Py_buffer *view,
791 int *view_active)
792 {
793 if (PyObject_CheckBuffer(arg)) {
794 if (PyObject_GetBuffer(arg, view, PyBUF_SIMPLE) != 0) {
795 return -1;
796 }
797
798 *view_active = 1;
799 *data = (char *)view->buf;
800 *data_len = view->len;
801 return 0;
802 }
803
804 if (PyBytes_Check(arg) || PyUnicode_Check(arg)) {
805 return PyText_AsStringAndSize(arg, data, data_len, encoded_obj);
806 }
807
808 PyErr_SetString(PyExc_TypeError,
809 "data() argument must be a byte string, ASCII-only Unicode string, or a buffer object");
810 return -1;
811 }
812
813 static int
814 curlmime_validate_text_arg(PyObject *obj, const char *name)
815 {
816 char *value;
817 PyObject *encoded_obj = NULL;
818
819 if (obj == NULL || obj == Py_None) {
820 return 0;
821 }
822
823 if (!PyText_Check(obj)) {
824 PyErr_Format(PyExc_TypeError, "%s must be a byte string or ascii-unicode string", name);
825 return -1;
826 }
827
828 value = PyText_AsString_NoNUL(obj, &encoded_obj);
829 Py_XDECREF(encoded_obj);
830 if (value == NULL) {
831 return -1;
832 }
833
834 return 0;
835 }
836
837 static int
838 curlmime_validate_data_arg(PyObject *obj)
839 {
840 Py_buffer view;
841 PyObject *encoded_obj = NULL;
842 char *data;
843 Py_ssize_t data_len = 0;
844 int view_active = 0;
845
846 if (obj == NULL || obj == Py_None) {
847 return 0;
848 }
849
850 if (curlmimepart_data_as_string_or_buffer(obj, &data, &data_len,
851 &encoded_obj, &view, &view_active) != 0)
852 {
853 return -1;
854 }
855
856 if (view_active) {
857 PyBuffer_Release(&view);
858 }
859 Py_XDECREF(encoded_obj);
860
861 return 0;
862 }
863
864 static int
865 curlmime_validate_file_arg(CurlMimeObject *self, PyObject *obj, const char *name)
866 {
867 FILE *fp;
868 char *path;
869 PyObject *encoded_obj = NULL;
870
871 if (obj == NULL || obj == Py_None) {
872 return 0;
873 }
874
875 if (curlmime_validate_text_arg(obj, name) != 0) {
876 return -1;
877 }
878
879 path = PyText_AsString_NoNUL(obj, &encoded_obj);
880 if (path == NULL) {
881 return -1;
882 }
883
884 fp = fopen(path, "rb");
885 Py_XDECREF(encoded_obj);
886 if (fp == NULL) {
887 curlmime_set_error(self != NULL ? self->curl : NULL, CURLE_READ_ERROR);
888 return -1;
889 }
890 fclose(fp);
891 return 0;
892 }
893
894 static int
895 curlmime_validate_headers_arg(PyObject *obj)
896 {
897 struct curl_slist *slist;
898
899 if (obj == NULL || obj == Py_None) {
900 return 0;
901 }
902
903 slist = curlmime_headers_to_slist(obj);
904 if (slist == NULL) {
905 return PyErr_Occurred() ? -1 : 0;
906 }
907
908 curl_slist_free_all(slist);
909 return 0;
910 }
911
912 static int
913 curlmime_validate_builder_args(CurlMimeObject *self,
914 PyObject *name_obj,
915 PyObject *data_obj,
916 PyObject *file_obj,
917 PyObject *filename_obj,
918 PyObject *content_type_obj,
919 PyObject *headers_obj,
920 PyObject *encoder_obj)
921 {
922 if (data_obj != NULL && data_obj != Py_None &&
923 file_obj != NULL && file_obj != Py_None)
924 {
925 PyErr_SetString(PyExc_ValueError, "add() accepts at most one of data or file");
926 return -1;
927 }
928 if (curlmime_validate_text_arg(name_obj, "name") != 0) {
929 return -1;
930 }
931 if (curlmime_validate_data_arg(data_obj) != 0) {
932 return -1;
933 }
934 if (curlmime_validate_file_arg(self, file_obj, "file") != 0) {
935 return -1;
936 }
937 if (curlmime_validate_text_arg(filename_obj, "filename") != 0) {
938 return -1;
939 }
940 if (curlmime_validate_text_arg(content_type_obj, "content_type") != 0) {
941 return -1;
942 }
943 if (curlmime_validate_headers_arg(headers_obj) != 0) {
944 return -1;
945 }
946 if (curlmime_validate_text_arg(encoder_obj, "encoder") != 0) {
947 return -1;
948 }
949 return 0;
950 }
951
952 static int
953 curlmime_add_apply(CurlMimePartObject *part,
954 PyObject *name_obj,
955 PyObject *data_obj,
956 PyObject *file_obj,
957 PyObject *filename_obj,
958 PyObject *content_type_obj,
959 PyObject *headers_obj,
960 PyObject *encoder_obj)
961 {
962 PyObject *rv;
963
964 if (name_obj != NULL && name_obj != Py_None) {
965 rv = do_curlmimepart_name(part, name_obj);
966 if (rv == NULL) {
967 return -1;
968 }
969 Py_DECREF(rv);
970 }
971
972 if (data_obj != NULL && data_obj != Py_None) {
973 rv = do_curlmimepart_data(part, data_obj);
974 if (rv == NULL) {
975 return -1;
976 }
977 Py_DECREF(rv);
978 } else if (file_obj != NULL && file_obj != Py_None) {
979 rv = do_curlmimepart_filedata(part, file_obj);
980 if (rv == NULL) {
981 return -1;
982 }
983 Py_DECREF(rv);
984 }
985
986 if (filename_obj != NULL && filename_obj != Py_None) {
987 rv = do_curlmimepart_filename(part, filename_obj);
988 if (rv == NULL) {
989 return -1;
990 }
991 Py_DECREF(rv);
992 }
993
994 if (content_type_obj != NULL && content_type_obj != Py_None) {
995 rv = do_curlmimepart_type(part, content_type_obj);
996 if (rv == NULL) {
997 return -1;
998 }
999 Py_DECREF(rv);
1000 }
1001
1002 if (headers_obj != NULL && headers_obj != Py_None) {
1003 rv = do_curlmimepart_headers(part, headers_obj);
1004 if (rv == NULL) {
1005 return -1;
1006 }
1007 Py_DECREF(rv);
1008 }
1009
1010 if (encoder_obj != NULL && encoder_obj != Py_None) {
1011 rv = do_curlmimepart_encoder(part, encoder_obj);
1012 if (rv == NULL) {
1013 return -1;
1014 }
1015 Py_DECREF(rv);
1016 }
1017
1018 return 0;
1019 }
1020
1021 static PyObject *
1022 do_curlmime_add(CurlMimeObject *self, PyObject *args, PyObject *kwds)
1023 {
1024 PyObject *name_obj = NULL;
1025 PyObject *data_obj = NULL;
1026 PyObject *file_obj = NULL;
1027 PyObject *filename_obj = NULL;
1028 PyObject *content_type_obj = NULL;
1029 PyObject *headers_obj = NULL;
1030 PyObject *encoder_obj = NULL;
1031 PyObject *part_obj;
1032 static char *kwlist[] = {
1033 "name", "data", "file", "filename", "content_type", "headers", "encoder", NULL
1034 };
1035
1036 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOOO:add", kwlist,
1037 &name_obj, &data_obj, &file_obj, &filename_obj,
1038 &content_type_obj, &headers_obj, &encoder_obj))
1039 {
1040 return NULL;
1041 }
1042
1043 if (curlmime_validate_builder_args(self, name_obj, data_obj, file_obj, filename_obj,
1044 content_type_obj, headers_obj, encoder_obj) != 0)
1045 {
1046 return NULL;
1047 }
1048
1049 part_obj = do_curlmime_addpart(self, NULL);
1050 if (part_obj == NULL) {
1051 return NULL;
1052 }
1053
1054 if (curlmime_add_apply((CurlMimePartObject *)part_obj,
1055 name_obj, data_obj, file_obj, filename_obj,
1056 content_type_obj, headers_obj, encoder_obj) != 0)
1057 {
1058 Py_DECREF(part_obj);
1059 return NULL;
1060 }
1061
1062 return part_obj;
1063 }
1064
1065 static PyObject *
1066 do_curlmime_add_field(CurlMimeObject *self, PyObject *args, PyObject *kwds)
1067 {
1068 PyObject *name_obj;
1069 PyObject *value_obj;
1070 PyObject *content_type_obj = NULL;
1071 PyObject *encoder_obj = NULL;
1072 PyObject *headers_obj = NULL;
1073 PyObject *part_obj;
1074 static char *kwlist[] = {"name", "value", "content_type", "encoder", "headers", NULL};
1075
1076 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OOO:add_field", kwlist,
1077 &name_obj, &value_obj, &content_type_obj, &encoder_obj, &headers_obj))
1078 {
1079 return NULL;
1080 }
1081
1082 if (curlmime_validate_builder_args(self, name_obj, value_obj, NULL, NULL,
1083 content_type_obj, headers_obj, encoder_obj) != 0)
1084 {
1085 return NULL;
1086 }
1087
1088 part_obj = do_curlmime_addpart(self, NULL);
1089 if (part_obj == NULL) {
1090 return NULL;
1091 }
1092
1093 if (curlmime_add_apply((CurlMimePartObject *)part_obj,
1094 name_obj, value_obj, NULL, NULL,
1095 content_type_obj, headers_obj, encoder_obj) != 0)
1096 {
1097 Py_DECREF(part_obj);
1098 return NULL;
1099 }
1100
1101 return part_obj;
1102 }
1103
1104 static PyObject *
1105 do_curlmime_add_file(CurlMimeObject *self, PyObject *args, PyObject *kwds)
1106 {
1107 PyObject *name_obj;
1108 PyObject *path_obj;
1109 PyObject *filename_obj = NULL;
1110 PyObject *content_type_obj = NULL;
1111 PyObject *headers_obj = NULL;
1112 PyObject *encoder_obj = NULL;
1113 PyObject *part_obj;
1114 static char *kwlist[] = {"name", "path", "filename", "content_type", "headers", "encoder", NULL};
1115
1116 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OOOO:add_file", kwlist,
1117 &name_obj, &path_obj, &filename_obj, &content_type_obj, &headers_obj, &encoder_obj))
1118 {
1119 return NULL;
1120 }
1121
1122 if (curlmime_validate_builder_args(self, name_obj, NULL, path_obj, filename_obj,
1123 content_type_obj, headers_obj, encoder_obj) != 0)
1124 {
1125 return NULL;
1126 }
1127
1128 part_obj = do_curlmime_addpart(self, NULL);
1129 if (part_obj == NULL) {
1130 return NULL;
1131 }
1132
1133 if (curlmime_add_apply((CurlMimePartObject *)part_obj,
1134 name_obj, NULL, path_obj, filename_obj,
1135 content_type_obj, headers_obj, encoder_obj) != 0)
1136 {
1137 Py_DECREF(part_obj);
1138 return NULL;
1139 }
1140
1141 return part_obj;
1142 }
1143
1144 static PyObject *
1145 do_curlmime_add_multipart(CurlMimeObject *self, PyObject *args, PyObject *kwds)
1146 {
1147 PyObject *name_obj = NULL;
1148 PyObject *subtype_obj = NULL;
1149 PyObject *subtype_ref = NULL;
1150 PyObject *child_obj = NULL;
1151 PyObject *part_obj = NULL;
1152 PyObject *rv = NULL;
1153 PyObject *content_type_obj = NULL;
1154 PyObject *encoded_obj = NULL;
1155 char *subtype = NULL;
1156 static char *kwlist[] = {"name", "subtype", NULL};
1157
1158 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:add_multipart", kwlist, &name_obj, &subtype_obj)) {
1159 return NULL;
1160 }
1161
1162 if (curlmime_validate_text_arg(name_obj, "name") != 0) {
1163 return NULL;
1164 }
1165 if (subtype_obj != NULL && subtype_obj != Py_None &&
1166 curlmime_validate_text_arg(subtype_obj, "subtype") != 0)
1167 {
1168 return NULL;
1169 }
1170
1171 if (subtype_obj == NULL) {
1172 subtype_ref = PyUnicode_FromString("mixed");
1173 if (subtype_ref == NULL) {
1174 return NULL;
1175 }
1176 } else {
1177 subtype_ref = Py_NewRef(subtype_obj);
1178 }
1179
1180 if (subtype_ref != Py_None) {
1181 subtype = PyText_AsString_NoNUL(subtype_ref, &encoded_obj);
1182 if (subtype == NULL) {
1183 goto error;
1184 }
1185
1186 content_type_obj = PyUnicode_FromFormat("multipart/%s", subtype);
1187 Py_XDECREF(encoded_obj);
1188 encoded_obj = NULL;
1189 if (content_type_obj == NULL) {
1190 goto error;
1191 }
1192 }
1193
1194 child_obj = PyObject_CallFunctionObjArgs((PyObject *)p_CurlMime_Type, (PyObject *)self->curl, NULL);
1195 if (child_obj == NULL) {
1196 goto error;
1197 }
1198
1199 part_obj = do_curlmime_addpart(self, NULL);
1200 if (part_obj == NULL) {
1201 goto error;
1202 }
1203
1204 if (name_obj != NULL && name_obj != Py_None) {
1205 rv = do_curlmimepart_name((CurlMimePartObject *)part_obj, name_obj);
1206 if (rv == NULL) {
1207 goto error;
1208 }
1209 Py_CLEAR(rv);
1210 }
1211
1212 rv = do_curlmimepart_subparts((CurlMimePartObject *)part_obj, child_obj);
1213 if (rv == NULL) {
1214 goto error;
1215 }
1216 Py_CLEAR(rv);
1217
1218 if (content_type_obj != NULL) {
1219 rv = do_curlmimepart_type((CurlMimePartObject *)part_obj, content_type_obj);
1220 if (rv == NULL) {
1221 goto error;
1222 }
1223 Py_CLEAR(rv);
1224 }
1225
1226 Py_CLEAR(content_type_obj);
1227 Py_CLEAR(subtype_ref);
1228 Py_CLEAR(part_obj);
1229 return child_obj;
1230
1231 error:
1232 Py_XDECREF(rv);
1233 Py_XDECREF(encoded_obj);
1234 Py_XDECREF(content_type_obj);
1235 Py_XDECREF(subtype_ref);
1236 Py_XDECREF(child_obj);
1237 Py_XDECREF(part_obj);
1238 return NULL;
1239 }
1240
1241 static void
1242 curlmime_duphandle_incref_data_cb_owners_recursive(CurlMimeObject *mime)
1243 {
1244 Py_ssize_t i;
1245 Py_ssize_t len;
1246
1247 if (mime == NULL) {
1248 return;
1249 }
1250
1251 if (mime->data_cb_owners != NULL) {
1252 len = PyList_GET_SIZE(mime->data_cb_owners);
1253 for (i = 0; i < len; i++) {
1254 PyObject *owner_obj = PyList_GET_ITEM(mime->data_cb_owners, i);
1255 if (PyObject_TypeCheck(owner_obj, &CurlMimeDataCbOwner_Type)) {
1256 curlmime_data_cb_owner_add_libcurl_ref((CurlMimeDataCbOwner *)owner_obj);
1257 }
1258 }
1259 }
1260
1261 if (mime->submimes != NULL) {
1262 len = PyList_GET_SIZE(mime->submimes);
1263 for (i = 0; i < len; i++) {
1264 PyObject *submime_obj = PyList_GET_ITEM(mime->submimes, i);
1265 if (PyObject_TypeCheck(submime_obj, p_CurlMime_Type)) {
1266 curlmime_duphandle_incref_data_cb_owners_recursive((CurlMimeObject *)submime_obj);
1267 }
1268 }
1269 }
1270 }
1271
1272 PYCURL_INTERNAL void
1273 curlmime_duphandle_incref_data_cb_owners(PyObject *mime_obj)
1274 {
1275 if (mime_obj == NULL || !PyObject_TypeCheck(mime_obj, p_CurlMime_Type)) {
1276 return;
1277 }
1278
1279 curlmime_duphandle_incref_data_cb_owners_recursive((CurlMimeObject *)mime_obj);
1280 }
1281
1282 static PyMethodDef curlmimeobject_methods[] = {
1283 {"add", (PyCFunction)do_curlmime_add, METH_VARARGS | METH_KEYWORDS, "Add a part using a keyword-oriented builder API."},
1284 {"add_field", (PyCFunction)do_curlmime_add_field, METH_VARARGS | METH_KEYWORDS, "Add a simple form field part."},
1285 {"add_file", (PyCFunction)do_curlmime_add_file, METH_VARARGS | METH_KEYWORDS, "Add a file upload part."},
1286 {"add_multipart", (PyCFunction)do_curlmime_add_multipart, METH_VARARGS | METH_KEYWORDS, "Add and attach a nested multipart CurlMime."},
1287 {"close", (PyCFunction)do_curlmime_close, METH_NOARGS, "Release the underlying curl_mime handle."},
1288 {"closed", (PyCFunction)do_curlmime_closed, METH_NOARGS, "Return whether this CurlMime object is closed."},
1289 {"addpart", (PyCFunction)do_curlmime_addpart, METH_NOARGS, "Create and return a new MIME part."},
1290 {"__enter__", (PyCFunction)do_curlmime_enter, METH_NOARGS, NULL},
1291 {"__exit__", (PyCFunction)do_curlmime_exit, METH_VARARGS, NULL},
1292 {NULL, NULL, 0, NULL}
1293 };
1294
1295 static PyTypeObject CurlMimeDataCbOwner_Type = {
1296 PyVarObject_HEAD_INIT(NULL, 0)
1297 "pycurl._MimeDataCbOwner", /* tp_name */
1298 sizeof(CurlMimeDataCbOwner), /* tp_basicsize */
1299 0, /* tp_itemsize */
1300 (destructor)curlmime_data_cb_owner_dealloc, /* tp_dealloc */
1301 0, /* tp_print / tp_vectorcall_offset */
1302 0, /* tp_getattr */
1303 0, /* tp_setattr */
1304 0, /* tp_reserved / tp_as_async */
1305 0, /* tp_repr */
1306 0, /* tp_as_number */
1307 0, /* tp_as_sequence */
1308 0, /* tp_as_mapping */
1309 0, /* tp_hash */
1310 0, /* tp_call */
1311 0, /* tp_str */
1312 0, /* tp_getattro */
1313 0, /* tp_setattro */
1314 0, /* tp_as_buffer */
1315 PYCURL_TYPE_FLAGS, /* tp_flags */
1316 "Internal owner for curl_mime_data_cb callbacks.", /* tp_doc */
1317 (traverseproc)curlmime_data_cb_owner_traverse, /* tp_traverse */
1318 (inquiry)curlmime_data_cb_owner_clear, /* tp_clear */
1319 0, /* tp_richcompare */
1320 0, /* tp_weaklistoffset */
1321 0, /* tp_iter */
1322 0, /* tp_iternext */
1323 0, /* tp_methods */
1324 0, /* tp_members */
1325 0, /* tp_getset */
1326 0, /* tp_base */
1327 0, /* tp_dict */
1328 0, /* tp_descr_get */
1329 0, /* tp_descr_set */
1330 0, /* tp_dictoffset */
1331 0, /* tp_init */
1332 PyType_GenericAlloc, /* tp_alloc */
1333 0, /* tp_new */
1334 PyObject_GC_Del, /* tp_free */
1335 };
1336
1337 PYCURL_INTERNAL PyTypeObject CurlMime_Type = {
1338 PyVarObject_HEAD_INIT(NULL, 0)
1339 "pycurl.CurlMime", /* tp_name */
1340 sizeof(CurlMimeObject), /* tp_basicsize */
1341 0, /* tp_itemsize */
1342 (destructor)do_curlmime_dealloc, /* tp_dealloc */
1343 0, /* tp_print / tp_vectorcall_offset */
1344 0, /* tp_getattr */
1345 0, /* tp_setattr */
1346 0, /* tp_reserved / tp_as_async */
1347 0, /* tp_repr */
1348 0, /* tp_as_number */
1349 0, /* tp_as_sequence */
1350 0, /* tp_as_mapping */
1351 0, /* tp_hash */
1352 0, /* tp_call */
1353 0, /* tp_str */
1354 0, /* tp_getattro */
1355 0, /* tp_setattro */
1356 0, /* tp_as_buffer */
1357 PYCURL_TYPE_FLAGS, /* tp_flags */
1358 "Python wrapper for libcurl MIME API.", /* tp_doc */
1359 (traverseproc)do_curlmime_traverse, /* tp_traverse */
1360 (inquiry)do_curlmime_clear, /* tp_clear */
1361 0, /* tp_richcompare */
1362 0, /* tp_weaklistoffset */
1363 0, /* tp_iter */
1364 0, /* tp_iternext */
1365 curlmimeobject_methods, /* tp_methods */
1366 0, /* tp_members */
1367 0, /* tp_getset */
1368 0, /* tp_base */
1369 0, /* tp_dict */
1370 0, /* tp_descr_get */
1371 0, /* tp_descr_set */
1372 0, /* tp_dictoffset */
1373 0, /* tp_init */
1374 PyType_GenericAlloc, /* tp_alloc */
1375 (newfunc)do_curlmime_new, /* tp_new */
1376 PyObject_GC_Del, /* tp_free */
1377 };
1378
1379 static int
1380 do_curlmimepart_traverse(CurlMimePartObject *self, visitproc visit, void *arg)
1381 {
1382 int err;
1383 #undef VISIT
1384 #define VISIT(v) if ((v) != NULL && ((err = visit(v, arg)) != 0)) return err
1385
1386 VISIT((PyObject *)self->mime);
1387 VISIT(self->data_cb_owner);
1388
1389 return 0;
1390 #undef VISIT
1391 }
1392
1393 static int
1394 do_curlmimepart_clear(CurlMimePartObject *self)
1395 {
1396 Py_CLEAR(self->data_cb_owner);
1397 Py_CLEAR(self->mime);
1398 self->part = NULL;
1399 return 0;
1400 }
1401
1402 static void
1403 do_curlmimepart_dealloc(CurlMimePartObject *self)
1404 {
1405 PyObject_GC_UnTrack(self);
1406 Py_TRASHCAN_BEGIN(self, do_curlmimepart_dealloc);
1407 do_curlmimepart_clear(self);
1408 CurlMimePart_Type.tp_free(self);
1409 Py_TRASHCAN_END;
1410 }
1411
1412 static PyObject *
1413 do_curlmimepart_name(CurlMimePartObject *self, PyObject *arg)
1414 {
1415 PyObject *encoded_obj = NULL;
1416 char *name;
1417 int res;
1418
1419 if (curlmimepart_check_state(self, "name") != 0) {
1420 return NULL;
1421 }
1422
1423 name = PyText_AsString_NoNUL(arg, &encoded_obj);
1424 if (name == NULL) {
1425 return NULL;
1426 }
1427
1428 res = (int)curl_mime_name(self->part, name);
1429 Py_XDECREF(encoded_obj);
1430 if (res != CURLE_OK) {
1431 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1432 return NULL;
1433 }
1434
1435 Py_RETURN_NONE;
1436 }
1437
1438 static PyObject *
1439 do_curlmimepart_data(CurlMimePartObject *self, PyObject *arg)
1440 {
1441 Py_buffer view;
1442 PyObject *encoded_obj = NULL;
1443 char *data;
1444 Py_ssize_t data_len = 0;
1445 int view_active = 0;
1446 int res;
1447
1448 if (curlmimepart_check_state(self, "data") != 0) {
1449 return NULL;
1450 }
1451
1452 if (curlmimepart_data_as_string_or_buffer(arg, &data, &data_len,
1453 &encoded_obj, &view, &view_active) != 0)
1454 {
1455 return NULL;
1456 }
1457
1458 res = (int)curl_mime_data(self->part, data, (size_t)data_len);
1459 if (view_active) {
1460 PyBuffer_Release(&view);
1461 }
1462 Py_XDECREF(encoded_obj);
1463 if (res != CURLE_OK) {
1464 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1465 return NULL;
1466 }
1467 if (curlmimepart_drop_data_cb_owner(self) != 0) {
1468 return NULL;
1469 }
1470
1471 Py_RETURN_NONE;
1472 }
1473
1474 static int
1475 curlmimepart_parse_datasize(PyObject *datasize_obj, curl_off_t *datasize)
1476 {
1477 PY_LONG_LONG value;
1478
1479 if (datasize_obj == Py_None) {
1480 *datasize = (curl_off_t)-1;
1481 return 0;
1482 }
1483
1484 value = PyLong_AsLongLong(datasize_obj);
1485 if (value == -1 && PyErr_Occurred()) {
1486 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1487 PyErr_SetString(PyExc_TypeError, "datasize must be an integer >= -1 or None");
1488 }
1489 return -1;
1490 }
1491 if ((curl_off_t)value != value) {
1492 PyErr_SetString(PyExc_OverflowError, "datasize does not fit into curl_off_t");
1493 return -1;
1494 }
1495 if (value < -1) {
1496 PyErr_SetString(PyExc_ValueError, "datasize must be >= -1");
1497 return -1;
1498 }
1499
1500 *datasize = (curl_off_t)value;
1501 return 0;
1502 }
1503
1504 static PyObject *
1505 do_curlmimepart_data_cb(CurlMimePartObject *self, PyObject *args, PyObject *kwds)
1506 {
1507 PyObject *datasize_obj;
1508 PyObject *read_cb;
1509 PyObject *seek_cb = Py_None;
1510 PyObject *free_cb = Py_None;
1511 PyObject *userdata = Py_None;
1512 CurlMimeDataCbOwner *owner = NULL;
1513 PyObject *owners = NULL;
1514 PyObject *old_owner_obj;
1515 curl_read_callback readfunc = curlmimepart_read_callback;
1516 curl_seek_callback seekfunc = NULL;
1517 curl_off_t datasize;
1518 int res;
1519 static char *kwlist[] = {"datasize", "read", "seek", "free", "userdata", NULL};
1520
1521 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OOO:data_cb", kwlist,
1522 &datasize_obj, &read_cb, &seek_cb, &free_cb, &userdata))
1523 {
1524 return NULL;
1525 }
1526
1527 if (curlmimepart_check_state(self, "data_cb") != 0) {
1528 return NULL;
1529 }
1530 if (curlmimepart_parse_datasize(datasize_obj, &datasize) != 0) {
1531 return NULL;
1532 }
1533 if (!PyCallable_Check(read_cb)) {
1534 PyErr_SetString(PyExc_TypeError, "read must be callable");
1535 return NULL;
1536 }
1537 if (seek_cb != Py_None && !PyCallable_Check(seek_cb)) {
1538 PyErr_SetString(PyExc_TypeError, "seek must be callable or None");
1539 return NULL;
1540 }
1541 if (free_cb != Py_None && !PyCallable_Check(free_cb)) {
1542 PyErr_SetString(PyExc_TypeError, "free must be callable or None");
1543 return NULL;
1544 }
1545 if (self->mime->data_cb_owners == NULL) {
1546 PyErr_SetString(ErrorObject, "data_cb() cannot attach to a closed mime object");
1547 return NULL;
1548 }
1549
1550 owner = curlmime_data_cb_owner_new(read_cb, seek_cb, free_cb, userdata);
1551 if (owner == NULL) {
1552 return NULL;
1553 }
1554 if (seek_cb != Py_None) {
1555 seekfunc = curlmimepart_seek_callback;
1556 }
1557
1558 owners = self->mime->data_cb_owners;
1559 if (PyList_Append(owners, (PyObject *)owner) != 0) {
1560 Py_DECREF(owner);
1561 return NULL;
1562 }
1563
1564 /* Keep one reference per libcurl owner that can invoke freefunc. */
1565 curlmime_data_cb_owner_add_libcurl_ref(owner);
1566
1567 res = (int)curl_mime_data_cb(self->part, datasize, readfunc, seekfunc,
1568 curlmimepart_free_callback, owner);
1569 if (res != CURLE_OK) {
1570 if (curlmime_owner_list_remove_ptr(owners, (PyObject *)owner) != 0) {
1571 PyErr_Clear();
1572 }
1573 curlmime_data_cb_owner_release_libcurl_ref(owner, 0);
1574 Py_DECREF(owner);
1575 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1576 return NULL;
1577 }
1578
1579 old_owner_obj = self->data_cb_owner;
1580 if (old_owner_obj != NULL) {
1581 if (curlmime_owner_list_remove_ptr(owners, old_owner_obj) != 0) {
1582 PyErr_Clear();
1583 }
1584 }
1585 Py_INCREF(owner);
1586 self->data_cb_owner = (PyObject *)owner;
1587 Py_XDECREF(old_owner_obj);
1588 Py_DECREF(owner);
1589
1590 Py_RETURN_NONE;
1591 }
1592
1593 static PyObject *
1594 do_curlmimepart_filedata(CurlMimePartObject *self, PyObject *arg)
1595 {
1596 PyObject *encoded_obj = NULL;
1597 char *path;
1598 int res;
1599
1600 if (curlmimepart_check_state(self, "filedata") != 0) {
1601 return NULL;
1602 }
1603
1604 path = PyText_AsString_NoNUL(arg, &encoded_obj);
1605 if (path == NULL) {
1606 return NULL;
1607 }
1608
1609 res = (int)curl_mime_filedata(self->part, path);
1610 Py_XDECREF(encoded_obj);
1611 if (res != CURLE_OK) {
1612 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1613 return NULL;
1614 }
1615 if (curlmimepart_drop_data_cb_owner(self) != 0) {
1616 return NULL;
1617 }
1618
1619 Py_RETURN_NONE;
1620 }
1621
1622 static PyObject *
1623 do_curlmimepart_filename(CurlMimePartObject *self, PyObject *arg)
1624 {
1625 PyObject *encoded_obj = NULL;
1626 char *name;
1627 int res;
1628
1629 if (curlmimepart_check_state(self, "filename") != 0) {
1630 return NULL;
1631 }
1632
1633 name = PyText_AsString_NoNUL(arg, &encoded_obj);
1634 if (name == NULL) {
1635 return NULL;
1636 }
1637
1638 res = (int)curl_mime_filename(self->part, name);
1639 Py_XDECREF(encoded_obj);
1640 if (res != CURLE_OK) {
1641 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1642 return NULL;
1643 }
1644
1645 Py_RETURN_NONE;
1646 }
1647
1648 static PyObject *
1649 do_curlmimepart_type(CurlMimePartObject *self, PyObject *arg)
1650 {
1651 PyObject *encoded_obj = NULL;
1652 char *type;
1653 int res;
1654
1655 if (curlmimepart_check_state(self, "type") != 0) {
1656 return NULL;
1657 }
1658
1659 type = PyText_AsString_NoNUL(arg, &encoded_obj);
1660 if (type == NULL) {
1661 return NULL;
1662 }
1663
1664 res = (int)curl_mime_type(self->part, type);
1665 Py_XDECREF(encoded_obj);
1666 if (res != CURLE_OK) {
1667 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1668 return NULL;
1669 }
1670
1671 Py_RETURN_NONE;
1672 }
1673
1674 static PyObject *
1675 do_curlmimepart_encoder(CurlMimePartObject *self, PyObject *arg)
1676 {
1677 PyObject *encoded_obj = NULL;
1678 char *encoding;
1679 int res;
1680
1681 if (curlmimepart_check_state(self, "encoder") != 0) {
1682 return NULL;
1683 }
1684
1685 encoding = PyText_AsString_NoNUL(arg, &encoded_obj);
1686 if (encoding == NULL) {
1687 return NULL;
1688 }
1689
1690 res = (int)curl_mime_encoder(self->part, encoding);
1691 Py_XDECREF(encoded_obj);
1692 if (res != CURLE_OK) {
1693 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1694 return NULL;
1695 }
1696
1697 Py_RETURN_NONE;
1698 }
1699
1700 static PyObject *
1701 do_curlmimepart_headers(CurlMimePartObject *self, PyObject *arg)
1702 {
1703 struct curl_slist *slist;
1704 int res;
1705
1706 if (curlmimepart_check_state(self, "headers") != 0) {
1707 return NULL;
1708 }
1709
1710 slist = curlmime_headers_to_slist(arg);
1711 if (slist == NULL && arg != Py_None && PyErr_Occurred()) {
1712 return NULL;
1713 }
1714
1715 res = (int)curl_mime_headers(self->part, slist, 1);
1716 if (res != CURLE_OK) {
1717 if (slist != NULL) {
1718 curl_slist_free_all(slist);
1719 }
1720 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1721 return NULL;
1722 }
1723
1724 Py_RETURN_NONE;
1725 }
1726
1727 static PyObject *
1728 do_curlmimepart_subparts(CurlMimePartObject *self, PyObject *arg)
1729 {
1730 CurlMimeObject *submime;
1731 Py_ssize_t item_index;
1732 int res;
1733
1734 if (!PyObject_TypeCheck(arg, p_CurlMime_Type)) {
1735 PyErr_SetString(PyExc_TypeError, "subparts() expects a CurlMime object");
1736 return NULL;
1737 }
1738
1739 submime = (CurlMimeObject *)arg;
1740
1741 if (curlmimepart_check_state(self, "subparts") != 0) {
1742 return NULL;
1743 }
1744 if (submime->mime == NULL) {
1745 PyErr_SetString(PyExc_ValueError, "subparts() received a closed mime object");
1746 return NULL;
1747 }
1748 if (submime->curl != self->mime->curl) {
1749 PyErr_SetString(PyExc_ValueError, "subparts() requires both mime objects to use the same Curl handle");
1750 return NULL;
1751 }
1752 if (submime == self->mime) {
1753 PyErr_SetString(PyExc_ValueError, "subparts() does not accept the parent mime object");
1754 return NULL;
1755 }
1756 if (!submime->owns_mime) {
1757 PyErr_SetString(PyExc_ValueError, "subparts() received a mime object already attached as subparts");
1758 return NULL;
1759 }
1760 if (submime->curl != NULL && submime->curl->mimepost_obj == (PyObject *)submime) {
1761 PyErr_SetString(PyExc_ValueError, "subparts() received a mime object currently set as MIMEPOST");
1762 return NULL;
1763 }
1764 if (self->mime->submimes == NULL) {
1765 PyErr_SetString(ErrorObject, "subparts() cannot attach to a closed mime object");
1766 return NULL;
1767 }
1768 if (PyList_Append(self->mime->submimes, (PyObject *)submime) != 0) {
1769 return NULL;
1770 }
1771
1772 res = (int)curl_mime_subparts(self->part, submime->mime);
1773 if (res != CURLE_OK) {
1774 item_index = PyList_GET_SIZE(self->mime->submimes) - 1;
1775 if (item_index >= 0) {
1776 (void)PySequence_DelItem(self->mime->submimes, item_index);
1777 PyErr_Clear();
1778 }
1779 curlmime_set_error(self->mime != NULL ? self->mime->curl : NULL, res);
1780 return NULL;
1781 }
1782 submime->owns_mime = 0;
1783 if (curlmimepart_drop_data_cb_owner(self) != 0) {
1784 return NULL;
1785 }
1786
1787 Py_RETURN_NONE;
1788 }
1789
1790 static PyMethodDef curlmimepartobject_methods[] = {
1791 {"name", (PyCFunction)do_curlmimepart_name, METH_O, "Set the name of this MIME part."},
1792 {"data", (PyCFunction)do_curlmimepart_data, METH_O, "Set in-memory data for this MIME part."},
1793 {"data_cb", (PyCFunction)do_curlmimepart_data_cb, METH_VARARGS | METH_KEYWORDS, "Set callback-based data for this MIME part."},
1794 {"filedata", (PyCFunction)do_curlmimepart_filedata, METH_O, "Set on-disk file data for this MIME part."},
1795 {"filename", (PyCFunction)do_curlmimepart_filename, METH_O, "Set the remote filename for this MIME part."},
1796 {"type", (PyCFunction)do_curlmimepart_type, METH_O, "Set content type for this MIME part."},
1797 {"encoder", (PyCFunction)do_curlmimepart_encoder, METH_O, "Set content transfer encoding for this MIME part."},
1798 {"headers", (PyCFunction)do_curlmimepart_headers, METH_O, "Set custom headers for this MIME part."},
1799 {"subparts", (PyCFunction)do_curlmimepart_subparts, METH_O, "Attach a child CurlMime object as multipart data."},
1800 {NULL, NULL, 0, NULL}
1801 };
1802
1803 PYCURL_INTERNAL PyTypeObject CurlMimePart_Type = {
1804 PyVarObject_HEAD_INIT(NULL, 0)
1805 "pycurl.CurlMimePart", /* tp_name */
1806 sizeof(CurlMimePartObject), /* tp_basicsize */
1807 0, /* tp_itemsize */
1808 (destructor)do_curlmimepart_dealloc, /* tp_dealloc */
1809 0, /* tp_print / tp_vectorcall_offset */
1810 0, /* tp_getattr */
1811 0, /* tp_setattr */
1812 0, /* tp_reserved / tp_as_async */
1813 0, /* tp_repr */
1814 0, /* tp_as_number */
1815 0, /* tp_as_sequence */
1816 0, /* tp_as_mapping */
1817 0, /* tp_hash */
1818 0, /* tp_call */
1819 0, /* tp_str */
1820 0, /* tp_getattro */
1821 0, /* tp_setattro */
1822 0, /* tp_as_buffer */
1823 PYCURL_TYPE_FLAGS, /* tp_flags */
1824 "A MIME part belonging to a CurlMime object.", /* tp_doc */
1825 (traverseproc)do_curlmimepart_traverse, /* tp_traverse */
1826 (inquiry)do_curlmimepart_clear, /* tp_clear */
1827 0, /* tp_richcompare */
1828 0, /* tp_weaklistoffset */
1829 0, /* tp_iter */
1830 0, /* tp_iternext */
1831 curlmimepartobject_methods, /* tp_methods */
1832 0, /* tp_members */
1833 0, /* tp_getset */
1834 0, /* tp_base */
1835 0, /* tp_dict */
1836 0, /* tp_descr_get */
1837 0, /* tp_descr_set */
1838 0, /* tp_dictoffset */
1839 0, /* tp_init */
1840 PyType_GenericAlloc, /* tp_alloc */
1841 0, /* tp_new */
1842 PyObject_GC_Del, /* tp_free */
1843 };
1844
1845 #endif /* HAVE_CURL_MIME */