]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/request.c
e58beceeba59044c4f069ee6545a8dc0460b3ce0
[thirdparty/cups.git] / cups / request.c
1 /*
2 * IPP utilities for CUPS.
3 *
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products.
6 *
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
8 */
9
10 /*
11 * Include necessary headers...
12 */
13
14 #include "cups-private.h"
15 #include <fcntl.h>
16 #include <sys/stat.h>
17 #if defined(WIN32) || defined(__EMX__)
18 # include <io.h>
19 #else
20 # include <unistd.h>
21 #endif /* WIN32 || __EMX__ */
22 #ifndef O_BINARY
23 # define O_BINARY 0
24 #endif /* O_BINARY */
25 #ifndef MSG_DONTWAIT
26 # define MSG_DONTWAIT 0
27 #endif /* !MSG_DONTWAIT */
28
29
30 /*
31 * 'cupsDoFileRequest()' - Do an IPP request with a file.
32 *
33 * This function sends the IPP request and attached file to the specified
34 * server, retrying and authenticating as necessary. The request is freed with
35 * @link ippDelete@.
36 */
37
38 ipp_t * /* O - Response data */
39 cupsDoFileRequest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
40 ipp_t *request, /* I - IPP request */
41 const char *resource, /* I - HTTP resource for POST */
42 const char *filename) /* I - File to send or @code NULL@ for none */
43 {
44 ipp_t *response; /* IPP response data */
45 int infile; /* Input file */
46
47
48 DEBUG_printf(("cupsDoFileRequest(http=%p, request=%p(%s), resource=\"%s\", filename=\"%s\")", (void *)http, (void *)request, request ? ippOpString(request->request.op.operation_id) : "?", resource, filename));
49
50 if (filename)
51 {
52 if ((infile = open(filename, O_RDONLY | O_BINARY)) < 0)
53 {
54 /*
55 * Can't get file information!
56 */
57
58 _cupsSetError(errno == ENOENT ? IPP_STATUS_ERROR_NOT_FOUND : IPP_STATUS_ERROR_NOT_AUTHORIZED,
59 NULL, 0);
60
61 ippDelete(request);
62
63 return (NULL);
64 }
65 }
66 else
67 infile = -1;
68
69 response = cupsDoIORequest(http, request, resource, infile, -1);
70
71 if (infile >= 0)
72 close(infile);
73
74 return (response);
75 }
76
77
78 /*
79 * 'cupsDoIORequest()' - Do an IPP request with file descriptors.
80 *
81 * This function sends the IPP request with the optional input file "infile" to
82 * the specified server, retrying and authenticating as necessary. The request
83 * is freed with @link ippDelete@.
84 *
85 * If "infile" is a valid file descriptor, @code cupsDoIORequest@ copies
86 * all of the data from the file after the IPP request message.
87 *
88 * If "outfile" is a valid file descriptor, @code cupsDoIORequest@ copies
89 * all of the data after the IPP response message to the file.
90 *
91 * @since CUPS 1.3/macOS 10.5@
92 */
93
94 ipp_t * /* O - Response data */
95 cupsDoIORequest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
96 ipp_t *request, /* I - IPP request */
97 const char *resource, /* I - HTTP resource for POST */
98 int infile, /* I - File to read from or -1 for none */
99 int outfile) /* I - File to write to or -1 for none */
100 {
101 ipp_t *response = NULL; /* IPP response data */
102 size_t length = 0; /* Content-Length value */
103 http_status_t status; /* Status of HTTP request */
104 struct stat fileinfo; /* File information */
105 ssize_t bytes; /* Number of bytes read/written */
106 char buffer[32768]; /* Output buffer */
107
108
109 DEBUG_printf(("cupsDoIORequest(http=%p, request=%p(%s), resource=\"%s\", infile=%d, outfile=%d)", (void *)http, (void *)request, request ? ippOpString(request->request.op.operation_id) : "?", resource, infile, outfile));
110
111 /*
112 * Range check input...
113 */
114
115 if (!request || !resource)
116 {
117 ippDelete(request);
118
119 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
120
121 return (NULL);
122 }
123
124 /*
125 * Get the default connection as needed...
126 */
127
128 if (!http && (http = _cupsConnect()) == NULL)
129 {
130 ippDelete(request);
131
132 return (NULL);
133 }
134
135 /*
136 * See if we have a file to send...
137 */
138
139 if (infile >= 0)
140 {
141 if (fstat(infile, &fileinfo))
142 {
143 /*
144 * Can't get file information!
145 */
146
147 _cupsSetError(errno == EBADF ? IPP_STATUS_ERROR_NOT_FOUND : IPP_STATUS_ERROR_NOT_AUTHORIZED, NULL, 0);
148 ippDelete(request);
149
150 return (NULL);
151 }
152
153 #ifdef WIN32
154 if (fileinfo.st_mode & _S_IFDIR)
155 #else
156 if (S_ISDIR(fileinfo.st_mode))
157 #endif /* WIN32 */
158 {
159 /*
160 * Can't send a directory...
161 */
162
163 _cupsSetError(IPP_STATUS_ERROR_NOT_POSSIBLE, strerror(EISDIR), 0);
164 ippDelete(request);
165
166 return (NULL);
167 }
168
169 #ifndef WIN32
170 if (!S_ISREG(fileinfo.st_mode))
171 length = 0; /* Chunk when piping */
172 else
173 #endif /* !WIN32 */
174 length = ippLength(request) + (size_t)fileinfo.st_size;
175 }
176 else
177 length = ippLength(request);
178
179 DEBUG_printf(("2cupsDoIORequest: Request length=%ld, total length=%ld", (long)ippLength(request), (long)length));
180
181 /*
182 * Clear any "Local" authentication data since it is probably stale...
183 */
184
185 if (http->authstring && !strncmp(http->authstring, "Local ", 6))
186 httpSetAuthString(http, NULL, NULL);
187
188 /*
189 * Loop until we can send the request without authorization problems.
190 */
191
192 while (response == NULL)
193 {
194 DEBUG_puts("2cupsDoIORequest: setup...");
195
196 /*
197 * Send the request...
198 */
199
200 status = cupsSendRequest(http, request, resource, length);
201
202 DEBUG_printf(("2cupsDoIORequest: status=%d", status));
203
204 if (status == HTTP_STATUS_CONTINUE && request->state == IPP_STATE_DATA && infile >= 0)
205 {
206 DEBUG_puts("2cupsDoIORequest: file write...");
207
208 /*
209 * Send the file with the request...
210 */
211
212 #ifndef WIN32
213 if (S_ISREG(fileinfo.st_mode))
214 #endif /* WIN32 */
215 lseek(infile, 0, SEEK_SET);
216
217 while ((bytes = read(infile, buffer, sizeof(buffer))) > 0)
218 {
219 if ((status = cupsWriteRequestData(http, buffer, (size_t)bytes))
220 != HTTP_STATUS_CONTINUE)
221 break;
222 }
223 }
224
225 /*
226 * Get the server's response...
227 */
228
229 if (status <= HTTP_STATUS_CONTINUE || status == HTTP_STATUS_OK)
230 {
231 response = cupsGetResponse(http, resource);
232 status = httpGetStatus(http);
233 }
234
235 DEBUG_printf(("2cupsDoIORequest: status=%d", status));
236
237 if (status == HTTP_STATUS_ERROR ||
238 (status >= HTTP_STATUS_BAD_REQUEST && status != HTTP_STATUS_UNAUTHORIZED &&
239 status != HTTP_STATUS_UPGRADE_REQUIRED))
240 {
241 _cupsSetHTTPError(status);
242 break;
243 }
244
245 if (response && outfile >= 0)
246 {
247 /*
248 * Write trailing data to file...
249 */
250
251 while ((bytes = httpRead2(http, buffer, sizeof(buffer))) > 0)
252 if (write(outfile, buffer, (size_t)bytes) < bytes)
253 break;
254 }
255
256 if (http->state != HTTP_STATE_WAITING)
257 {
258 /*
259 * Flush any remaining data...
260 */
261
262 httpFlush(http);
263 }
264 }
265
266 /*
267 * Delete the original request and return the response...
268 */
269
270 ippDelete(request);
271
272 return (response);
273 }
274
275
276 /*
277 * 'cupsDoRequest()' - Do an IPP request.
278 *
279 * This function sends the IPP request to the specified server, retrying
280 * and authenticating as necessary. The request is freed with @link ippDelete@.
281 */
282
283 ipp_t * /* O - Response data */
284 cupsDoRequest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
285 ipp_t *request, /* I - IPP request */
286 const char *resource) /* I - HTTP resource for POST */
287 {
288 DEBUG_printf(("cupsDoRequest(http=%p, request=%p(%s), resource=\"%s\")", (void *)http, (void *)request, request ? ippOpString(request->request.op.operation_id) : "?", resource));
289
290 return (cupsDoIORequest(http, request, resource, -1, -1));
291 }
292
293
294 /*
295 * 'cupsGetResponse()' - Get a response to an IPP request.
296 *
297 * Use this function to get the response for an IPP request sent using
298 * @link cupsSendRequest@. For requests that return additional data, use
299 * @link cupsReadResponseData@ after getting a successful response,
300 * otherwise call @link httpFlush@ to complete the response processing.
301 *
302 * @since CUPS 1.4/macOS 10.6@
303 */
304
305 ipp_t * /* O - Response or @code NULL@ on HTTP error */
306 cupsGetResponse(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
307 const char *resource) /* I - HTTP resource for POST */
308 {
309 http_status_t status; /* HTTP status */
310 ipp_state_t state; /* IPP read state */
311 ipp_t *response = NULL; /* IPP response */
312
313
314 DEBUG_printf(("cupsGetResponse(http=%p, resource=\"%s\")", (void *)http, resource));
315 DEBUG_printf(("1cupsGetResponse: http->state=%d", http ? http->state : HTTP_STATE_ERROR));
316
317 /*
318 * Connect to the default server as needed...
319 */
320
321 if (!http)
322 {
323 _cups_globals_t *cg = _cupsGlobals();
324 /* Pointer to library globals */
325
326 if ((http = cg->http) == NULL)
327 {
328 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No active connection."), 1);
329 DEBUG_puts("1cupsGetResponse: No active connection - returning NULL.");
330 return (NULL);
331 }
332 }
333
334 if (http->state != HTTP_STATE_POST_RECV && http->state != HTTP_STATE_POST_SEND)
335 {
336 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request sent."), 1);
337 DEBUG_puts("1cupsGetResponse: Not in POST state - returning NULL.");
338 return (NULL);
339 }
340
341 /*
342 * Check for an unfinished chunked request...
343 */
344
345 if (http->data_encoding == HTTP_ENCODING_CHUNKED)
346 {
347 /*
348 * Send a 0-length chunk to finish off the request...
349 */
350
351 DEBUG_puts("2cupsGetResponse: Finishing chunked POST...");
352
353 if (httpWrite2(http, "", 0) < 0)
354 return (NULL);
355 }
356
357 /*
358 * Wait for a response from the server...
359 */
360
361 DEBUG_printf(("2cupsGetResponse: Update loop, http->status=%d...",
362 http->status));
363
364 do
365 {
366 status = httpUpdate(http);
367 }
368 while (status == HTTP_STATUS_CONTINUE);
369
370 DEBUG_printf(("2cupsGetResponse: status=%d", status));
371
372 if (status == HTTP_STATUS_OK)
373 {
374 /*
375 * Get the IPP response...
376 */
377
378 response = ippNew();
379
380 while ((state = ippRead(http, response)) != IPP_STATE_DATA)
381 if (state == IPP_STATE_ERROR)
382 break;
383
384 if (state == IPP_STATE_ERROR)
385 {
386 /*
387 * Flush remaining data and delete the response...
388 */
389
390 DEBUG_puts("1cupsGetResponse: IPP read error!");
391
392 httpFlush(http);
393
394 ippDelete(response);
395 response = NULL;
396
397 http->status = status = HTTP_STATUS_ERROR;
398 http->error = EINVAL;
399 }
400 }
401 else if (status != HTTP_STATUS_ERROR)
402 {
403 /*
404 * Flush any error message...
405 */
406
407 httpFlush(http);
408
409 /*
410 * Then handle encryption and authentication...
411 */
412
413 if (status == HTTP_STATUS_UNAUTHORIZED)
414 {
415 /*
416 * See if we can do authentication...
417 */
418
419 DEBUG_puts("2cupsGetResponse: Need authorization...");
420
421 if (!cupsDoAuthentication(http, "POST", resource))
422 httpReconnect2(http, 30000, NULL);
423 else
424 http->status = status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED;
425 }
426
427 #ifdef HAVE_SSL
428 else if (status == HTTP_STATUS_UPGRADE_REQUIRED)
429 {
430 /*
431 * Force a reconnect with encryption...
432 */
433
434 DEBUG_puts("2cupsGetResponse: Need encryption...");
435
436 if (!httpReconnect2(http, 30000, NULL))
437 httpEncryption(http, HTTP_ENCRYPTION_REQUIRED);
438 }
439 #endif /* HAVE_SSL */
440 }
441
442 if (response)
443 {
444 ipp_attribute_t *attr; /* status-message attribute */
445
446
447 attr = ippFindAttribute(response, "status-message", IPP_TAG_TEXT);
448
449 DEBUG_printf(("1cupsGetResponse: status-code=%s, status-message=\"%s\"",
450 ippErrorString(response->request.status.status_code),
451 attr ? attr->values[0].string.text : ""));
452
453 _cupsSetError(response->request.status.status_code,
454 attr ? attr->values[0].string.text :
455 ippErrorString(response->request.status.status_code), 0);
456 }
457
458 return (response);
459 }
460
461
462 /*
463 * 'cupsLastError()' - Return the last IPP status code received on the current
464 * thread.
465 */
466
467 ipp_status_t /* O - IPP status code from last request */
468 cupsLastError(void)
469 {
470 return (_cupsGlobals()->last_error);
471 }
472
473
474 /*
475 * 'cupsLastErrorString()' - Return the last IPP status-message received on the
476 * current thread.
477 *
478 * @since CUPS 1.2/macOS 10.5@
479 */
480
481 const char * /* O - status-message text from last request */
482 cupsLastErrorString(void)
483 {
484 return (_cupsGlobals()->last_status_message);
485 }
486
487
488 /*
489 * '_cupsNextDelay()' - Return the next retry delay value.
490 *
491 * This function currently returns the Fibonacci sequence 1 1 2 3 5 8.
492 *
493 * Pass 0 for the current delay value to initialize the sequence.
494 */
495
496 int /* O - Next delay value */
497 _cupsNextDelay(int current, /* I - Current delay value or 0 */
498 int *previous) /* IO - Previous delay value */
499 {
500 int next; /* Next delay value */
501
502
503 if (current > 0)
504 {
505 next = (current + *previous) % 12;
506 *previous = next < current ? 0 : current;
507 }
508 else
509 {
510 next = 1;
511 *previous = 0;
512 }
513
514 return (next);
515 }
516
517
518 /*
519 * 'cupsReadResponseData()' - Read additional data after the IPP response.
520 *
521 * This function is used after @link cupsGetResponse@ to read the PPD or document
522 * files from @code CUPS_GET_PPD@ and @code CUPS_GET_DOCUMENT@ requests,
523 * respectively.
524 *
525 * @since CUPS 1.4/macOS 10.6@
526 */
527
528 ssize_t /* O - Bytes read, 0 on EOF, -1 on error */
529 cupsReadResponseData(
530 http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
531 char *buffer, /* I - Buffer to use */
532 size_t length) /* I - Number of bytes to read */
533 {
534 /*
535 * Get the default connection as needed...
536 */
537
538 DEBUG_printf(("cupsReadResponseData(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
539
540 if (!http)
541 {
542 _cups_globals_t *cg = _cupsGlobals();
543 /* Pointer to library globals */
544
545 if ((http = cg->http) == NULL)
546 {
547 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No active connection"), 1);
548 return (-1);
549 }
550 }
551
552 /*
553 * Then read from the HTTP connection...
554 */
555
556 return (httpRead2(http, buffer, length));
557 }
558
559
560 /*
561 * 'cupsSendRequest()' - Send an IPP request.
562 *
563 * Use @link cupsWriteRequestData@ to write any additional data (document, PPD
564 * file, etc.) for the request, @link cupsGetResponse@ to get the IPP response,
565 * and @link cupsReadResponseData@ to read any additional data following the
566 * response. Only one request can be sent/queued at a time per @code http_t@
567 * connection.
568 *
569 * Returns the initial HTTP status code, which will be @code HTTP_STATUS_CONTINUE@
570 * on a successful send of the request.
571 *
572 * Note: Unlike @link cupsDoFileRequest@, @link cupsDoIORequest@, and
573 * @link cupsDoRequest@, the request is NOT freed with @link ippDelete@.
574 *
575 * @since CUPS 1.4/macOS 10.6@
576 */
577
578 http_status_t /* O - Initial HTTP status */
579 cupsSendRequest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
580 ipp_t *request, /* I - IPP request */
581 const char *resource, /* I - Resource path */
582 size_t length) /* I - Length of data to follow or @code CUPS_LENGTH_VARIABLE@ */
583 {
584 http_status_t status; /* Status of HTTP request */
585 int got_status; /* Did we get the status? */
586 ipp_state_t state; /* State of IPP processing */
587 http_status_t expect; /* Expect: header to use */
588 char date[256]; /* Date: header value */
589 int digest; /* Are we using Digest authentication? */
590
591
592 DEBUG_printf(("cupsSendRequest(http=%p, request=%p(%s), resource=\"%s\", length=" CUPS_LLFMT ")", (void *)http, (void *)request, request ? ippOpString(request->request.op.operation_id) : "?", resource, CUPS_LLCAST length));
593
594 /*
595 * Range check input...
596 */
597
598 if (!request || !resource)
599 {
600 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
601
602 return (HTTP_STATUS_ERROR);
603 }
604
605 /*
606 * Get the default connection as needed...
607 */
608
609 if (!http && (http = _cupsConnect()) == NULL)
610 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
611
612 /*
613 * If the prior request was not flushed out, do so now...
614 */
615
616 if (http->state == HTTP_STATE_GET_SEND ||
617 http->state == HTTP_STATE_POST_SEND)
618 {
619 DEBUG_puts("2cupsSendRequest: Flush prior response.");
620 httpFlush(http);
621 }
622 else if (http->state != HTTP_STATE_WAITING)
623 {
624 DEBUG_printf(("1cupsSendRequest: Unknown HTTP state (%d), "
625 "reconnecting.", http->state));
626 if (httpReconnect2(http, 30000, NULL))
627 return (HTTP_STATUS_ERROR);
628 }
629
630 #ifdef HAVE_SSL
631 /*
632 * See if we have an auth-info attribute and are communicating over
633 * a non-local link. If so, encrypt the link so that we can pass
634 * the authentication information securely...
635 */
636
637 if (ippFindAttribute(request, "auth-info", IPP_TAG_TEXT) &&
638 !httpAddrLocalhost(http->hostaddr) && !http->tls &&
639 httpEncryption(http, HTTP_ENCRYPTION_REQUIRED))
640 {
641 DEBUG_puts("1cupsSendRequest: Unable to encrypt connection.");
642 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
643 }
644 #endif /* HAVE_SSL */
645
646 /*
647 * Reconnect if the last response had a "Connection: close"...
648 */
649
650 if (!_cups_strcasecmp(httpGetField(http, HTTP_FIELD_CONNECTION), "close"))
651 {
652 DEBUG_puts("2cupsSendRequest: Connection: close");
653 httpClearFields(http);
654 if (httpReconnect2(http, 30000, NULL))
655 {
656 DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
657 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
658 }
659 }
660
661 /*
662 * Loop until we can send the request without authorization problems.
663 */
664
665 expect = HTTP_STATUS_CONTINUE;
666
667 for (;;)
668 {
669 DEBUG_puts("2cupsSendRequest: Setup...");
670
671 /*
672 * Setup the HTTP variables needed...
673 */
674
675 httpClearFields(http);
676 httpSetExpect(http, expect);
677 httpSetField(http, HTTP_FIELD_CONTENT_TYPE, "application/ipp");
678 httpSetField(http, HTTP_FIELD_DATE, httpGetDateString2(time(NULL), date, (int)sizeof(date)));
679 httpSetLength(http, length);
680
681 digest = http->authstring && !strncmp(http->authstring, "Digest ", 7);
682
683 if (digest)
684 {
685 /*
686 * Update the Digest authentication string...
687 */
688
689 _httpSetDigestAuthString(http, http->nextnonce, "POST", resource);
690 }
691
692 #ifdef HAVE_GSSAPI
693 if (http->authstring && !strncmp(http->authstring, "Negotiate", 9))
694 {
695 /*
696 * Do not use cached Kerberos credentials since they will look like a
697 * "replay" attack...
698 */
699
700 _cupsSetNegotiateAuthString(http, "POST", resource);
701 }
702 #endif /* HAVE_GSSAPI */
703
704 httpSetField(http, HTTP_FIELD_AUTHORIZATION, http->authstring);
705
706 DEBUG_printf(("2cupsSendRequest: authstring=\"%s\"", http->authstring));
707
708 /*
709 * Try the request...
710 */
711
712 DEBUG_puts("2cupsSendRequest: Sending HTTP POST...");
713
714 if (httpPost(http, resource))
715 {
716 DEBUG_puts("2cupsSendRequest: POST failed, reconnecting.");
717 if (httpReconnect2(http, 30000, NULL))
718 {
719 DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
720 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
721 }
722 else
723 continue;
724 }
725
726 /*
727 * Send the IPP data...
728 */
729
730 DEBUG_puts("2cupsSendRequest: Writing IPP request...");
731
732 request->state = IPP_STATE_IDLE;
733 status = HTTP_STATUS_CONTINUE;
734 got_status = 0;
735
736 while ((state = ippWrite(http, request)) != IPP_STATE_DATA)
737 {
738 if (httpCheck(http))
739 {
740 got_status = 1;
741
742 _httpUpdate(http, &status);
743 if (status >= HTTP_STATUS_MULTIPLE_CHOICES)
744 break;
745 }
746 else if (state == IPP_STATE_ERROR)
747 break;
748 }
749
750 if (state == IPP_STATE_ERROR)
751 {
752 /*
753 * We weren't able to send the IPP request. But did we already get a HTTP
754 * error status?
755 */
756
757 if (!got_status || status < HTTP_STATUS_MULTIPLE_CHOICES)
758 {
759 /*
760 * No, something else went wrong.
761 */
762
763 DEBUG_puts("1cupsSendRequest: Unable to send IPP request.");
764
765 http->status = HTTP_STATUS_ERROR;
766 http->state = HTTP_STATE_WAITING;
767
768 return (HTTP_STATUS_ERROR);
769 }
770 }
771
772 /*
773 * Wait up to 1 second to get the 100-continue response as needed...
774 */
775
776 if (!got_status || (digest && status == HTTP_STATUS_CONTINUE))
777 {
778 if (expect == HTTP_STATUS_CONTINUE || digest)
779 {
780 DEBUG_puts("2cupsSendRequest: Waiting for 100-continue...");
781
782 if (httpWait(http, 1000))
783 _httpUpdate(http, &status);
784 }
785 else if (httpCheck(http))
786 _httpUpdate(http, &status);
787 }
788
789 DEBUG_printf(("2cupsSendRequest: status=%d", status));
790
791 /*
792 * Process the current HTTP status...
793 */
794
795 if (status >= HTTP_STATUS_MULTIPLE_CHOICES)
796 {
797 int temp_status; /* Temporary status */
798
799 _cupsSetHTTPError(status);
800
801 do
802 {
803 temp_status = httpUpdate(http);
804 }
805 while (temp_status != HTTP_STATUS_ERROR &&
806 http->state == HTTP_STATE_POST_RECV);
807
808 httpFlush(http);
809 }
810
811 switch (status)
812 {
813 case HTTP_STATUS_CONTINUE :
814 case HTTP_STATUS_OK :
815 case HTTP_STATUS_ERROR :
816 DEBUG_printf(("1cupsSendRequest: Returning %d.", status));
817 return (status);
818
819 case HTTP_STATUS_UNAUTHORIZED :
820 if (cupsDoAuthentication(http, "POST", resource))
821 {
822 DEBUG_puts("1cupsSendRequest: Returning HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED.");
823 return (HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED);
824 }
825
826 DEBUG_puts("2cupsSendRequest: Reconnecting after HTTP_STATUS_UNAUTHORIZED.");
827
828 if (httpReconnect2(http, 30000, NULL))
829 {
830 DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
831 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
832 }
833 break;
834
835 #ifdef HAVE_SSL
836 case HTTP_STATUS_UPGRADE_REQUIRED :
837 /*
838 * Flush any error message, reconnect, and then upgrade with
839 * encryption...
840 */
841
842 DEBUG_puts("2cupsSendRequest: Reconnecting after "
843 "HTTP_STATUS_UPGRADE_REQUIRED.");
844
845 if (httpReconnect2(http, 30000, NULL))
846 {
847 DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
848 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
849 }
850
851 DEBUG_puts("2cupsSendRequest: Upgrading to TLS.");
852 if (httpEncryption(http, HTTP_ENCRYPTION_REQUIRED))
853 {
854 DEBUG_puts("1cupsSendRequest: Unable to encrypt connection.");
855 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
856 }
857 break;
858 #endif /* HAVE_SSL */
859
860 case HTTP_STATUS_EXPECTATION_FAILED :
861 /*
862 * Don't try using the Expect: header the next time around...
863 */
864
865 expect = (http_status_t)0;
866
867 DEBUG_puts("2cupsSendRequest: Reconnecting after "
868 "HTTP_EXPECTATION_FAILED.");
869
870 if (httpReconnect2(http, 30000, NULL))
871 {
872 DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
873 return (HTTP_STATUS_SERVICE_UNAVAILABLE);
874 }
875 break;
876
877 default :
878 /*
879 * Some other error...
880 */
881
882 return (status);
883 }
884 }
885 }
886
887
888 /*
889 * 'cupsWriteRequestData()' - Write additional data after an IPP request.
890 *
891 * This function is used after @link cupsSendRequest@ to provide a PPD and
892 * after @link cupsStartDocument@ to provide a document file.
893 *
894 * @since CUPS 1.4/macOS 10.6@
895 */
896
897 http_status_t /* O - @code HTTP_STATUS_CONTINUE@ if OK or HTTP status on error */
898 cupsWriteRequestData(
899 http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
900 const char *buffer, /* I - Bytes to write */
901 size_t length) /* I - Number of bytes to write */
902 {
903 int wused; /* Previous bytes in buffer */
904
905
906 /*
907 * Get the default connection as needed...
908 */
909
910 DEBUG_printf(("cupsWriteRequestData(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
911
912 if (!http)
913 {
914 _cups_globals_t *cg = _cupsGlobals();
915 /* Pointer to library globals */
916
917 if ((http = cg->http) == NULL)
918 {
919 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No active connection"), 1);
920 DEBUG_puts("1cupsWriteRequestData: Returning HTTP_STATUS_ERROR.");
921 return (HTTP_STATUS_ERROR);
922 }
923 }
924
925 /*
926 * Then write to the HTTP connection...
927 */
928
929 wused = http->wused;
930
931 if (httpWrite2(http, buffer, length) < 0)
932 {
933 DEBUG_puts("1cupsWriteRequestData: Returning HTTP_STATUS_ERROR.");
934 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(http->error), 0);
935 return (HTTP_STATUS_ERROR);
936 }
937
938 /*
939 * Finally, check if we have any pending data from the server...
940 */
941
942 if (length >= HTTP_MAX_BUFFER ||
943 http->wused < wused ||
944 (wused > 0 && (size_t)http->wused == length))
945 {
946 /*
947 * We've written something to the server, so check for response data...
948 */
949
950 if (_httpWait(http, 0, 1))
951 {
952 http_status_t status; /* Status from _httpUpdate */
953
954 _httpUpdate(http, &status);
955 if (status >= HTTP_STATUS_MULTIPLE_CHOICES)
956 {
957 _cupsSetHTTPError(status);
958
959 do
960 {
961 status = httpUpdate(http);
962 }
963 while (status != HTTP_STATUS_ERROR && http->state == HTTP_STATE_POST_RECV);
964
965 httpFlush(http);
966 }
967
968 DEBUG_printf(("1cupsWriteRequestData: Returning %d.\n", status));
969 return (status);
970 }
971 }
972
973 DEBUG_puts("1cupsWriteRequestData: Returning HTTP_STATUS_CONTINUE.");
974 return (HTTP_STATUS_CONTINUE);
975 }
976
977
978 /*
979 * '_cupsConnect()' - Get the default server connection...
980 */
981
982 http_t * /* O - HTTP connection */
983 _cupsConnect(void)
984 {
985 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
986
987
988 /*
989 * See if we are connected to the same server...
990 */
991
992 if (cg->http)
993 {
994 /*
995 * Compare the connection hostname, port, and encryption settings to
996 * the cached defaults; these were initialized the first time we
997 * connected...
998 */
999
1000 if (strcmp(cg->http->hostname, cg->server) ||
1001 #ifdef AF_LOCAL
1002 (httpAddrFamily(cg->http->hostaddr) != AF_LOCAL && cg->ipp_port != httpAddrPort(cg->http->hostaddr)) ||
1003 #else
1004 cg->ipp_port != httpAddrPort(cg->http->hostaddr) ||
1005 #endif /* AF_LOCAL */
1006 (cg->http->encryption != cg->encryption &&
1007 cg->http->encryption == HTTP_ENCRYPTION_NEVER))
1008 {
1009 /*
1010 * Need to close the current connection because something has changed...
1011 */
1012
1013 httpClose(cg->http);
1014 cg->http = NULL;
1015 }
1016 else
1017 {
1018 /*
1019 * Same server, see if the connection is still established...
1020 */
1021
1022 char ch; /* Connection check byte */
1023 ssize_t n; /* Number of bytes */
1024
1025 #ifdef WIN32
1026 if ((n = recv(cg->http->fd, &ch, 1, MSG_PEEK)) == 0 ||
1027 (n < 0 && WSAGetLastError() != WSAEWOULDBLOCK))
1028 #else
1029 if ((n = recv(cg->http->fd, &ch, 1, MSG_PEEK | MSG_DONTWAIT)) == 0 ||
1030 (n < 0 && errno != EWOULDBLOCK))
1031 #endif /* WIN32 */
1032 {
1033 /*
1034 * Nope, close the connection...
1035 */
1036
1037 httpClose(cg->http);
1038 cg->http = NULL;
1039 }
1040 }
1041 }
1042
1043 /*
1044 * (Re)connect as needed...
1045 */
1046
1047 if (!cg->http)
1048 {
1049 if ((cg->http = httpConnect2(cupsServer(), ippPort(), NULL, AF_UNSPEC,
1050 cupsEncryption(), 1, 30000, NULL)) == NULL)
1051 {
1052 if (errno)
1053 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE, NULL, 0);
1054 else
1055 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE,
1056 _("Unable to connect to host."), 1);
1057 }
1058 }
1059
1060 /*
1061 * Return the cached connection...
1062 */
1063
1064 return (cg->http);
1065 }
1066
1067
1068 /*
1069 * '_cupsSetError()' - Set the last IPP status code and status-message.
1070 */
1071
1072 void
1073 _cupsSetError(ipp_status_t status, /* I - IPP status code */
1074 const char *message, /* I - status-message value */
1075 int localize) /* I - Localize the message? */
1076 {
1077 _cups_globals_t *cg; /* Global data */
1078
1079
1080 if (!message && errno)
1081 {
1082 message = strerror(errno);
1083 localize = 0;
1084 }
1085
1086 cg = _cupsGlobals();
1087 cg->last_error = status;
1088
1089 if (cg->last_status_message)
1090 {
1091 _cupsStrFree(cg->last_status_message);
1092
1093 cg->last_status_message = NULL;
1094 }
1095
1096 if (message)
1097 {
1098 if (localize)
1099 {
1100 /*
1101 * Get the message catalog...
1102 */
1103
1104 if (!cg->lang_default)
1105 cg->lang_default = cupsLangDefault();
1106
1107 cg->last_status_message = _cupsStrAlloc(_cupsLangString(cg->lang_default,
1108 message));
1109 }
1110 else
1111 cg->last_status_message = _cupsStrAlloc(message);
1112 }
1113
1114 DEBUG_printf(("4_cupsSetError: last_error=%s, last_status_message=\"%s\"",
1115 ippErrorString(cg->last_error), cg->last_status_message));
1116 }
1117
1118
1119 /*
1120 * '_cupsSetHTTPError()' - Set the last error using the HTTP status.
1121 */
1122
1123 void
1124 _cupsSetHTTPError(http_status_t status) /* I - HTTP status code */
1125 {
1126 switch (status)
1127 {
1128 case HTTP_STATUS_NOT_FOUND :
1129 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, httpStatus(status), 0);
1130 break;
1131
1132 case HTTP_STATUS_UNAUTHORIZED :
1133 _cupsSetError(IPP_STATUS_ERROR_NOT_AUTHENTICATED, httpStatus(status), 0);
1134 break;
1135
1136 case HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED :
1137 _cupsSetError(IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED, httpStatus(status), 0);
1138 break;
1139
1140 case HTTP_STATUS_FORBIDDEN :
1141 _cupsSetError(IPP_STATUS_ERROR_FORBIDDEN, httpStatus(status), 0);
1142 break;
1143
1144 case HTTP_STATUS_BAD_REQUEST :
1145 _cupsSetError(IPP_STATUS_ERROR_BAD_REQUEST, httpStatus(status), 0);
1146 break;
1147
1148 case HTTP_STATUS_REQUEST_TOO_LARGE :
1149 _cupsSetError(IPP_STATUS_ERROR_REQUEST_VALUE, httpStatus(status), 0);
1150 break;
1151
1152 case HTTP_STATUS_NOT_IMPLEMENTED :
1153 _cupsSetError(IPP_STATUS_ERROR_OPERATION_NOT_SUPPORTED, httpStatus(status), 0);
1154 break;
1155
1156 case HTTP_STATUS_NOT_SUPPORTED :
1157 _cupsSetError(IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED, httpStatus(status), 0);
1158 break;
1159
1160 case HTTP_STATUS_UPGRADE_REQUIRED :
1161 _cupsSetError(IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED, httpStatus(status), 0);
1162 break;
1163
1164 case HTTP_STATUS_CUPS_PKI_ERROR :
1165 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, httpStatus(status), 0);
1166 break;
1167
1168 case HTTP_STATUS_ERROR :
1169 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
1170 break;
1171
1172 default :
1173 DEBUG_printf(("4_cupsSetHTTPError: HTTP error %d mapped to "
1174 "IPP_STATUS_ERROR_SERVICE_UNAVAILABLE!", status));
1175 _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE, httpStatus(status), 0);
1176 break;
1177 }
1178 }