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