From: Michael R Sweet Date: Fri, 8 Sep 2023 16:37:59 +0000 (-0400) Subject: Fix builds... X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=fd2496a67dde06b7dbe4f436e218c7309afdda99;p=thirdparty%2Fcups.git Fix builds... --- diff --git a/cups/adminutil.c b/cups/adminutil.c index b846e52d32..439936bc51 100644 --- a/cups/adminutil.c +++ b/cups/adminutil.c @@ -505,8 +505,7 @@ cupsAdminSetServerSettings( else old_debug_logging = 0; - DEBUG_printf(("1cupsAdminSetServerSettings: old debug_logging=%d", - old_debug_logging)); + DEBUG_printf("1cupsAdminSetServerSettings: old debug_logging=%d", old_debug_logging); if ((val = cupsGetOption(CUPS_SERVER_REMOTE_ADMIN, cupsd_num_settings, cupsd_settings)) != NULL) @@ -514,8 +513,7 @@ cupsAdminSetServerSettings( else old_remote_admin = 0; - DEBUG_printf(("1cupsAdminSetServerSettings: old remote_admin=%d", - old_remote_admin)); + DEBUG_printf("1cupsAdminSetServerSettings: old remote_admin=%d", old_remote_admin); if ((val = cupsGetOption(CUPS_SERVER_REMOTE_ANY, cupsd_num_settings, cupsd_settings)) != NULL) @@ -523,8 +521,7 @@ cupsAdminSetServerSettings( else old_remote_any = 0; - DEBUG_printf(("1cupsAdminSetServerSettings: old remote_any=%d", - old_remote_any)); + DEBUG_printf("1cupsAdminSetServerSettings: old remote_any=%d", old_remote_any); if ((val = cupsGetOption(CUPS_SERVER_SHARE_PRINTERS, cupsd_num_settings, cupsd_settings)) != NULL) @@ -532,8 +529,7 @@ cupsAdminSetServerSettings( else old_share_printers = 0; - DEBUG_printf(("1cupsAdminSetServerSettings: old share_printers=%d", - old_share_printers)); + DEBUG_printf("1cupsAdminSetServerSettings: old share_printers=%d", old_share_printers); if ((val = cupsGetOption(CUPS_SERVER_USER_CANCEL_ANY, cupsd_num_settings, cupsd_settings)) != NULL) @@ -541,8 +537,7 @@ cupsAdminSetServerSettings( else old_user_cancel_any = 0; - DEBUG_printf(("1cupsAdminSetServerSettings: old user_cancel_any=%d", - old_user_cancel_any)); + DEBUG_printf("1cupsAdminSetServerSettings: old user_cancel_any=%d", old_user_cancel_any); cupsFreeOptions(cupsd_num_settings, cupsd_settings); @@ -567,8 +562,7 @@ cupsAdminSetServerSettings( else debug_logging = -1; - DEBUG_printf(("1cupsAdminSetServerSettings: debug_logging=%d", - debug_logging)); + DEBUG_printf("1cupsAdminSetServerSettings: debug_logging=%d", debug_logging); if ((val = cupsGetOption(CUPS_SERVER_REMOTE_ANY, num_settings, settings)) != NULL) { @@ -605,8 +599,7 @@ cupsAdminSetServerSettings( else remote_admin = -1; - DEBUG_printf(("1cupsAdminSetServerSettings: remote_admin=%d", - remote_admin)); + DEBUG_printf("1cupsAdminSetServerSettings: remote_admin=%d", remote_admin); if ((val = cupsGetOption(CUPS_SERVER_SHARE_PRINTERS, num_settings, settings)) != NULL) @@ -625,8 +618,7 @@ cupsAdminSetServerSettings( else share_printers = -1; - DEBUG_printf(("1cupsAdminSetServerSettings: share_printers=%d", - share_printers)); + DEBUG_printf("1cupsAdminSetServerSettings: share_printers=%d", share_printers); if ((val = cupsGetOption(CUPS_SERVER_USER_CANCEL_ANY, num_settings, settings)) != NULL) @@ -645,8 +637,7 @@ cupsAdminSetServerSettings( else user_cancel_any = -1; - DEBUG_printf(("1cupsAdminSetServerSettings: user_cancel_any=%d", - user_cancel_any)); + DEBUG_printf("1cupsAdminSetServerSettings: user_cancel_any=%d", user_cancel_any); /* * Create a temporary file for the new cupsd.conf file... diff --git a/cups/array.c b/cups/array.c index 07d7139dc3..c590ed4f59 100644 --- a/cups/array.c +++ b/cups/array.c @@ -178,8 +178,7 @@ _cupsArrayAddStrings(cups_array_t *a, /* I - Array */ else end = start + strlen(start); - DEBUG_printf(("1_cupsArrayAddStrings: Adding \"%s\", end=\"%s\"", start, - end)); + DEBUG_printf("1_cupsArrayAddStrings: Adding \"%s\", end=\"%s\"", start, end); if (!cupsArrayFind(a, start)) status &= cupsArrayAdd(a, start); @@ -1262,8 +1261,7 @@ cups_array_find(cups_array_t *a, /* I - Array */ current = (left + right) / 2; diff = (*(a->compare))(e, a->elements[current], a->data); - DEBUG_printf(("9cups_array_find: left=%d, right=%d, current=%d, diff=%d", - left, right, current, diff)); + DEBUG_printf("9cups_array_find: left=%d, right=%d, current=%d, diff=%d", left, right, current, diff); if (diff == 0) break; diff --git a/cups/auth.c b/cups/auth.c index 279bb0321c..4f474af76b 100644 --- a/cups/auth.c +++ b/cups/auth.c @@ -128,10 +128,8 @@ cupsDoAuthentication( if (!http || !method || !resource) return (-1); - DEBUG_printf(("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"", - http->digest_tries, http->userpass)); - DEBUG_printf(("2cupsDoAuthentication: WWW-Authenticate=\"%s\"", - httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE))); + DEBUG_printf("2cupsDoAuthentication: digest_tries=%d, userpass=\"%s\"", http->digest_tries, http->userpass); + DEBUG_printf("2cupsDoAuthentication: WWW-Authenticate=\"%s\"", httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE)); /* * Clear the current authentication string... @@ -147,8 +145,7 @@ cupsDoAuthentication( { if ((localauth = cups_local_auth(http)) == 0) { - DEBUG_printf(("2cupsDoAuthentication: authstring=\"%s\"", - http->authstring)); + DEBUG_printf("2cupsDoAuthentication: authstring=\"%s\"", http->authstring); if (http->status == HTTP_STATUS_UNAUTHORIZED) http->digest_tries ++; @@ -523,8 +520,7 @@ _cupsSetNegotiateAuthString( } else { - DEBUG_printf(("1_cupsSetNegotiateAuthString: Kerberos credentials too " - "large - %d bytes!", (int)output_token.length)); + DEBUG_printf("1_cupsSetNegotiateAuthString: Kerberos credentials too large - %d bytes!", (int)output_token.length); gss_release_buffer(&minor_status, &output_token); return (CUPS_GSS_FAIL); @@ -833,9 +829,7 @@ cups_gss_getname( char buf[1024]; /* Name buffer */ - DEBUG_printf(("7cups_gss_getname(http=%p, service_name=\"%s\")", http, - service_name)); - + DEBUG_printf("7cups_gss_getname(http=%p, service_name=\"%s\")", http, service_name); /* * Get the hostname... @@ -849,8 +843,7 @@ cups_gss_getname( { if (gethostname(http->gsshost, sizeof(http->gsshost)) < 0) { - DEBUG_printf(("1cups_gss_getname: gethostname() failed: %s", - strerror(errno))); + DEBUG_printf("1cups_gss_getname: gethostname() failed: %s", strerror(errno)); http->gsshost[0] = '\0'; return (NULL); } @@ -873,8 +866,7 @@ cups_gss_getname( } else { - DEBUG_printf(("1cups_gss_getname: gethostbyname(\"%s\") failed.", - http->gsshost)); + DEBUG_printf("1cups_gss_getname: gethostbyname(\"%s\") failed.", http->gsshost); http->gsshost[0] = '\0'; return (NULL); } @@ -939,8 +931,7 @@ cups_gss_printf(OM_uint32 major_status,/* I - Major status code */ gss_display_status(&err_minor_status, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &minor_status_string); - DEBUG_printf(("1%s: %s, %s", message, (char *)major_status_string.value, - (char *)minor_status_string.value)); + DEBUG_printf("1%s: %s, %s", message, (char *)major_status_string.value, (char *)minor_status_string.value); gss_release_buffer(&err_minor_status, &major_status_string); gss_release_buffer(&err_minor_status, &minor_status_string); @@ -1022,8 +1013,7 @@ cups_local_auth(http_t *http) /* I - HTTP connection to server */ status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &http->auth_ref); if (status != errAuthorizationSuccess) { - DEBUG_printf(("8cups_local_auth: AuthorizationCreate() returned %d", - (int)status)); + DEBUG_printf("8cups_local_auth: AuthorizationCreate() returned %d", (int)status); return (-1); } @@ -1057,8 +1047,7 @@ cups_local_auth(http_t *http) /* I - HTTP connection to server */ httpSetAuthString(http, "AuthRef", buffer); - DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"", - http->authstring)); + DEBUG_printf("8cups_local_auth: Returning authstring=\"%s\"", http->authstring); return (0); } else if (status == errAuthorizationCanceled) @@ -1098,8 +1087,7 @@ cups_local_auth(http_t *http) /* I - HTTP connection to server */ { httpSetAuthString(http, "PeerCred", username); - DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"", - http->authstring)); + DEBUG_printf("8cups_local_auth: Returning authstring=\"%s\"", http->authstring); return (0); } @@ -1158,8 +1146,7 @@ cups_local_auth(http_t *http) /* I - HTTP connection to server */ httpSetAuthString(http, "Local", certificate); - DEBUG_printf(("8cups_local_auth: Returning authstring=\"%s\"", - http->authstring)); + DEBUG_printf("8cups_local_auth: Returning authstring=\"%s\"", http->authstring); return (0); } diff --git a/cups/backend.c b/cups/backend.c index 4f5099be50..5dfd217ae0 100644 --- a/cups/backend.c +++ b/cups/backend.c @@ -53,22 +53,21 @@ cupsBackendDeviceURI(char **argv) /* I - Command-line arguments */ device_uri = argv[0]; } - options = _HTTP_RESOLVE_STDERR; + options = 0 /*_HTTP_RESOLVE_STDERR*/; if ((auth_info_required = getenv("AUTH_INFO_REQUIRED")) != NULL && !strcmp(auth_info_required, "negotiate")) - options |= _HTTP_RESOLVE_FQDN; + options |= HTTP_RESOLVE_FQDN; if ((ppd = ppdOpenFile(getenv("PPD"))) != NULL) { if ((ppdattr = ppdFindAttr(ppd, "cupsIPPFaxOut", NULL)) != NULL && !_cups_strcasecmp(ppdattr->value, "true")) - options |= _HTTP_RESOLVE_FAXOUT; + options |= HTTP_RESOLVE_FAXOUT; ppdClose(ppd); } - return (_httpResolveURI(device_uri, cg->resolved_uri, - sizeof(cg->resolved_uri), options, NULL, NULL)); + return (httpResolveURI(device_uri, cg->resolved_uri, sizeof(cg->resolved_uri), options, NULL, NULL)); } diff --git a/cups/dest-localization.c b/cups/dest-localization.c index 0caafcec65..20871277e7 100644 --- a/cups/dest-localization.c +++ b/cups/dest-localization.c @@ -398,8 +398,7 @@ cups_create_localizations( if ((http2 = httpConnect2(hostname, port, NULL, AF_UNSPEC, encryption, 1, 30000, NULL)) == NULL) { - DEBUG_printf(("4cups_create_localizations: Unable to connect to " - "%s:%d: %s", hostname, port, cupsGetErrorString())); + DEBUG_printf("4cups_create_localizations: Unable to connect to %s:%d: %s", hostname, port, cupsGetErrorString()); return; } } @@ -410,8 +409,7 @@ cups_create_localizations( if ((temp = cupsTempFile2(tempfile, sizeof(tempfile))) == NULL) { - DEBUG_printf(("4cups_create_localizations: Unable to create temporary " - "file: %s", cupsGetErrorString())); + DEBUG_printf("4cups_create_localizations: Unable to create temporary file: %s", cupsGetErrorString()); if (http2 != http) httpClose(http2); return; @@ -431,8 +429,7 @@ cups_create_localizations( dinfo->localizations = _cupsMessageLoad(tempfile, _CUPS_MESSAGE_STRINGS); } - DEBUG_printf(("4cups_create_localizations: %d messages loaded.", - cupsArrayCount(dinfo->localizations))); + DEBUG_printf("4cups_create_localizations: %d messages loaded.", cupsArrayCount(dinfo->localizations)); /* * Cleanup... diff --git a/cups/dest-options.c b/cups/dest-options.c index caa9847339..4ca7fb6306 100644 --- a/cups/dest-options.c +++ b/cups/dest-options.c @@ -615,16 +615,14 @@ cupsCopyDestConflicts( if (cupsArrayFind(resolvers, c)) { - DEBUG_printf(("1cupsCopyDestConflicts: Resolver loop with %s.", - c->name)); + DEBUG_printf("1cupsCopyDestConflicts: Resolver loop with %s.", c->name); have_conflicts = -1; goto cleanup; } if ((r = cupsArrayFind(dinfo->resolvers, c)) == NULL) { - DEBUG_printf(("1cupsCopyDestConflicts: Resolver %s not found.", - c->name)); + DEBUG_printf("1cupsCopyDestConflicts: Resolver %s not found.", c->name); have_conflicts = -1; goto cleanup; } @@ -1490,8 +1488,7 @@ cupsGetDestMediaBySize( if ((pwg = pwgMediaForSize(width, length)) == NULL) { - DEBUG_printf(("1cupsGetDestMediaBySize: Invalid size %dx%d.", width, - length)); + DEBUG_printf("1cupsGetDestMediaBySize: Invalid size %dx%d.", width, length); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Invalid media size."), 1); return (0); } @@ -1563,8 +1560,7 @@ cupsGetDestMediaBySize2( if ((pwg = pwgMediaForSize(width, length)) == NULL) { - DEBUG_printf(("1cupsGetDestMediaBySize2: Invalid size %dx%d.", width, - length)); + DEBUG_printf("1cupsGetDestMediaBySize2: Invalid size %dx%d.", width, length); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Invalid media size."), 1); return (0); } @@ -2620,8 +2616,7 @@ cups_create_media_db( if ((pwg = pwgMediaForPWG(val->string.text)) == NULL) if ((pwg = pwgMediaForLegacy(val->string.text)) == NULL) { - DEBUG_printf(("3cups_create_media_db: Ignoring unknown size '%s'.", - val->string.text)); + DEBUG_printf("3cups_create_media_db: Ignoring unknown size '%s'.", val->string.text); continue; } diff --git a/cups/dest.c b/cups/dest.c index d385821def..872a6a30af 100644 --- a/cups/dest.c +++ b/cups/dest.c @@ -219,7 +219,7 @@ static void cups_dnssd_query_cb(AvahiRecordBrowser *browser, static const char *cups_dnssd_resolve(cups_dest_t *dest, const char *uri, int msec, int *cancel, cups_dest_cb_t cb, void *user_data); -static int cups_dnssd_resolve_cb(void *context); +static bool cups_dnssd_resolve_cb(void *context); static void cups_dnssd_unquote(char *dst, const char *src, size_t dstsize); static int cups_elapsed(struct timeval *t); @@ -382,8 +382,7 @@ _cupsAppleCopyDefaultPrinter(void) return (NULL); } - DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.", - (int)CFArrayGetCount(locations))); + DEBUG_printf("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.", (int)CFArrayGetCount(locations)); if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL) CFRetain(locprinter); @@ -2791,8 +2790,7 @@ cups_dnssd_get_device( _cupsStrFree(device->domain); device->domain = _cupsStrAlloc(replyDomain); - DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local " - "domain.", device->dest.name)); + DEBUG_printf("6cups_dnssd_get_device: Updating '%s' to use local domain.", device->dest.name); update = 1; } @@ -2807,16 +2805,14 @@ cups_dnssd_get_device( _cupsStrFree(device->regtype); device->regtype = _cupsStrAlloc(regtype); - DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.", - device->dest.name)); + DEBUG_printf("6cups_dnssd_get_device: Updating '%s' to use IPPS.", device->dest.name); update = 1; } if (!update) { - DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.", - device->dest.name)); + DEBUG_printf("6cups_dnssd_get_device: No changes to '%s'.", device->dest.name); return (device); } } @@ -2826,10 +2822,7 @@ cups_dnssd_get_device( * No, add the device... */ - DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain " - "'%s'.", serviceName, - !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP", - replyDomain)); + DEBUG_printf("6cups_dnssd_get_device: Adding '%s' for %s with domain '%s'.", serviceName, !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP", replyDomain); if ((device = calloc(1, sizeof(_cups_dnssd_device_t))) == NULL) return (NULL); @@ -3228,8 +3221,7 @@ cups_dnssd_query_cb( device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options); } else - DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.", - fullName)); + DEBUG_printf("6cups_dnssd_query: Ignoring TXT record for '%s'.", fullName); } @@ -3273,7 +3265,7 @@ cups_dnssd_resolve( if (cb) (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest); - if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL) + if ((uri = httpResolveURI(uri, tempuri, sizeof(tempuri), HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL) { _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1); @@ -3297,7 +3289,7 @@ cups_dnssd_resolve( * 'cups_dnssd_resolve_cb()' - See if we should continue resolving. */ -static int /* O - 1 to continue, 0 to stop */ +static bool /* O - `true` to continue, `false` to stop */ cups_dnssd_resolve_cb(void *context) /* I - Resolve data */ { _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context; @@ -3312,7 +3304,7 @@ cups_dnssd_resolve_cb(void *context) /* I - Resolve data */ if (resolve->cancel && *(resolve->cancel)) { DEBUG_puts("4cups_dnssd_resolve_cb: Canceled."); - return (0); + return (false); } /* @@ -4170,8 +4162,7 @@ cups_get_dests( * See what type of line it is... */ - DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"", - linenum, line, lineptr)); + DEBUG_printf("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"", linenum, line, lineptr); if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr) { @@ -4210,8 +4201,7 @@ cups_get_dests( if (*lineptr) *lineptr++ = '\0'; - DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name, - instance)); + DEBUG_printf("9cups_get_dests: name=\"%s\", instance=\"%s\"", name, instance); /* * Match and/or ignore missing destinations... diff --git a/cups/dir.c b/cups/dir.c index 721f55afbd..d807155086 100644 --- a/cups/dir.c +++ b/cups/dir.c @@ -392,8 +392,7 @@ cupsDirRead(cups_dir_t *dp) /* I - Directory pointer */ if (stat(filename, &(dp->entry.fileinfo))) { - DEBUG_printf(("3cupsDirRead: stat() failed for \"%s\" - %s...", filename, - strerror(errno))); + DEBUG_printf("3cupsDirRead: stat() failed for \"%s\" - %s...", filename, strerror(errno)); continue; } diff --git a/cups/file.c b/cups/file.c index 088c2a82a2..c595660891 100644 --- a/cups/file.c +++ b/cups/file.c @@ -629,8 +629,7 @@ cupsFileFlush(cups_file_t *fp) /* I - CUPS file */ bytes = (ssize_t)(fp->ptr - fp->buf); - DEBUG_printf(("2cupsFileFlush: Flushing " CUPS_LLFMT " bytes...", - CUPS_LLCAST bytes)); + DEBUG_printf("2cupsFileFlush: Flushing " CUPS_LLFMT " bytes...", CUPS_LLCAST bytes); if (bytes > 0) { @@ -725,8 +724,7 @@ cupsFileGetConf(cups_file_t *fp, /* I - CUPS file */ * Range check input... */ - DEBUG_printf(("2cupsFileGetConf(fp=%p, buf=%p, buflen=" CUPS_LLFMT - ", value=%p, linenum=%p)", (void *)fp, (void *)buf, CUPS_LLCAST buflen, (void *)value, (void *)linenum)); + DEBUG_printf("2cupsFileGetConf(fp=%p, buf=%p, buflen=" CUPS_LLFMT ", value=%p, linenum=%p)", (void *)fp, (void *)buf, CUPS_LLCAST buflen, (void *)value, (void *)linenum); if (!fp || (fp->mode != 'r' && fp->mode != 's') || !buf || buflen < 2 || !value) @@ -1078,8 +1076,7 @@ cupsFileOpen(const char *filename, /* I - Name of file */ http_addrlist_t *addrlist; /* Host address list */ - DEBUG_printf(("cupsFileOpen(filename=\"%s\", mode=\"%s\")", filename, - mode)); + DEBUG_printf("cupsFileOpen(filename=\"%s\", mode=\"%s\")", filename, mode); /* * Range check input... @@ -1668,8 +1665,7 @@ cupsFileRead(cups_file_t *fp, /* I - CUPS file */ if (fp->ptr >= fp->end) if (cups_fill(fp) <= 0) { - DEBUG_printf(("4cupsFileRead: cups_fill() returned -1, total=" - CUPS_LLFMT, CUPS_LLCAST total)); + DEBUG_printf("4cupsFileRead: cups_fill() returned -1, total=" CUPS_LLFMT, CUPS_LLCAST total); if (total > 0) return ((ssize_t)total); @@ -1887,8 +1883,7 @@ cupsFileSeek(cups_file_t *fp, /* I - CUPS file */ fp->ptr = NULL; fp->end = NULL; - DEBUG_printf(("2cupsFileSeek: lseek() returned " CUPS_LLFMT, - CUPS_LLCAST fp->pos)); + DEBUG_printf("2cupsFileSeek: lseek() returned " CUPS_LLFMT, CUPS_LLCAST fp->pos); } } else @@ -1922,8 +1917,7 @@ cupsFileSeek(cups_file_t *fp, /* I - CUPS file */ fp->ptr = NULL; fp->end = NULL; - DEBUG_printf(("2cupsFileSeek: lseek() returned " CUPS_LLFMT, - CUPS_LLCAST fp->pos)); + DEBUG_printf("2cupsFileSeek: lseek() returned " CUPS_LLFMT, CUPS_LLCAST fp->pos); } } @@ -2180,8 +2174,7 @@ cups_compress(cups_file_t *fp, /* I - CUPS file */ * Flush the current buffer... */ - DEBUG_printf(("9cups_compress: avail_in=%d, avail_out=%d", - fp->stream.avail_in, fp->stream.avail_out)); + DEBUG_printf("9cups_compress: avail_in=%d, avail_out=%d", fp->stream.avail_in, fp->stream.avail_out); if (fp->stream.avail_out < (uInt)(sizeof(fp->cbuf) / 8)) { @@ -2251,8 +2244,7 @@ cups_fill(cups_file_t *fp) /* I - CUPS file */ * Can't read from file! */ - DEBUG_printf(("9cups_fill: cups_read() returned " CUPS_LLFMT, - CUPS_LLCAST bytes)); + DEBUG_printf("9cups_fill: cups_read() returned " CUPS_LLFMT, CUPS_LLCAST bytes); fp->eof = 1; @@ -2270,8 +2262,7 @@ cups_fill(cups_file_t *fp) /* I - CUPS file */ fp->ptr = fp->buf; fp->end = fp->buf + bytes; - DEBUG_printf(("9cups_fill: Returning " CUPS_LLFMT, - CUPS_LLCAST bytes)); + DEBUG_printf("9cups_fill: Returning " CUPS_LLFMT, CUPS_LLCAST bytes); return (bytes); } diff --git a/cups/getdevices.c b/cups/getdevices.c index 4ce20158d3..9498054e58 100644 --- a/cups/getdevices.c +++ b/cups/getdevices.c @@ -191,8 +191,7 @@ cupsGetDevices( else attr = attr->next; - DEBUG_printf(("2cupsGetDevices: attr->name=\"%s\", attr->value_tag=%d", - attr->name, attr->value_tag)); + DEBUG_printf("2cupsGetDevices: attr->name=\"%s\", attr->value_tag=%d", attr->name, attr->value_tag); if (!attr->name) { @@ -247,9 +246,7 @@ cupsGetDevices( attr = ippFindAttribute(response, "status-message", IPP_TAG_TEXT); - DEBUG_printf(("cupsGetDevices: status-code=%s, status-message=\"%s\"", - ippErrorString(response->request.status.status_code), - attr ? attr->values[0].string.text : "")); + DEBUG_printf("cupsGetDevices: status-code=%s, status-message=\"%s\"", ippErrorString(response->request.status.status_code), attr ? attr->values[0].string.text : ""); _cupsSetError(response->request.status.status_code, attr ? attr->values[0].string.text : ippErrorString(response->request.status.status_code), 0); diff --git a/cups/getputfile.c b/cups/getputfile.c index ec57fa987a..d681b90fcb 100644 --- a/cups/getputfile.c +++ b/cups/getputfile.c @@ -332,8 +332,7 @@ cupsPutFd(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFA } } - DEBUG_printf(("2cupsPutFd: starting attempt, authstring=\"%s\"...", - http->authstring)); + DEBUG_printf("2cupsPutFd: starting attempt, authstring=\"%s\"...", http->authstring); httpClearFields(http); httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "chunked"); diff --git a/cups/http-private.h b/cups/http-private.h index 0681f16a14..e9b0200134 100644 --- a/cups/http-private.h +++ b/cups/http-private.h @@ -84,10 +84,6 @@ extern "C" { // # define _HTTP_MAX_SBUFFER 65536 /* Size of (de)compression buffer */ -# define _HTTP_RESOLVE_DEFAULT 0 /* Just resolve with default options */ -# define _HTTP_RESOLVE_STDERR 1 /* Log resolve progress to stderr */ -# define _HTTP_RESOLVE_FQDN 2 /* Resolve to a FQDN */ -# define _HTTP_RESOLVE_FAXOUT 4 /* Resolve FaxOut service? */ # define _HTTP_TLS_NONE 0 /* No TLS options */ # define _HTTP_TLS_ALLOW_RC4 1 /* Allow RC4 cipher suites */ @@ -252,8 +248,6 @@ extern char *_httpDecodeURI(char *dst, const char *src, size_t dstsize) _CUPS_P extern void _httpDisconnect(http_t *http) _CUPS_PRIVATE; extern char *_httpEncodeURI(char *dst, const char *src, size_t dstsize) _CUPS_PRIVATE; extern void _httpFreeCredentials(_http_tls_credentials_t *hcreds) _CUPS_PRIVATE; -// TODO: OK to remove _httpResolveURI? -extern const char *_httpResolveURI(const char *uri, char *resolved_uri, size_t resolved_size, int options, int (*cb)(void *context), void *context) _CUPS_PRIVATE; extern int _httpSetDigestAuthString(http_t *http, const char *nonce, const char *method, const char *resource) _CUPS_PRIVATE; extern const char *_httpStatusString(cups_lang_t *lang, http_status_t status) _CUPS_PRIVATE; extern void _httpTLSInitialize(void) _CUPS_PRIVATE; diff --git a/cups/http-support.c b/cups/http-support.c index 730b1b9c1d..f626cdbd09 100644 --- a/cups/http-support.c +++ b/cups/http-support.c @@ -1,59 +1,38 @@ -/* - * HTTP support routines for CUPS. - * - * Copyright © 2020-2023 by OpenPrinting - * Copyright © 2007-2019 by Apple Inc. - * Copyright © 1997-2007 by Easy Software Products, all rights reserved. - * - * Licensed under Apache License v2.0. See the file "LICENSE" for more - * information. - */ - -/* - * Include necessary headers... - */ +// +// HTTP support routines for CUPS. +// +// Copyright © 2020-2023 by OpenPrinting +// Copyright © 2007-2019 by Apple Inc. +// Copyright © 1997-2007 by Easy Software Products, all rights reserved. +// +// Licensed under Apache License v2.0. See the file "LICENSE" for more +// information. +// #include "cups-private.h" -#include "debug-internal.h" -#ifdef HAVE_MDNSRESPONDER -# include -# ifdef _WIN32 -# include -# elif defined(HAVE_POLL) -# include -# else -# include -# endif /* _WIN32 */ -#elif defined(HAVE_AVAHI) -# include -# include -# include -# include -#endif /* HAVE_MDNSRESPONDER */ - - -/* - * Local types... - */ - -typedef struct _http_uribuf_s /* URI buffer */ +#include "dnssd.h" + + +// +// Local types... +// + +typedef struct _http_uribuf_s // URI buffer { -#ifdef HAVE_AVAHI - AvahiSimplePoll *poll; /* Poll state */ -#endif /* HAVE_AVAHI */ - char *buffer; /* Pointer to buffer */ - size_t bufsize; /* Size of buffer */ - int options; /* Options passed to _httpResolveURI */ - const char *resource; /* Resource from URI */ - const char *uuid; /* UUID from URI */ + cups_dnssd_t *dnssd; // DNS-SD context + char *buffer; // Pointer to buffer + size_t bufsize; // Size of buffer + http_resolve_t options; // Options passed to httpResolveURI + const char *resource; // Resource from URI + const char *uuid; // UUID from URI } _http_uribuf_t; -/* - * Local globals... - */ +// +// Local globals... +// -static const char * const http_days[7] =/* Days of the week */ +static const char * const http_days[7] =// Days of the week { "Sun", "Mon", @@ -64,7 +43,7 @@ static const char * const http_days[7] =/* Days of the week */ "Sat" }; static const char * const http_months[12] = - { /* Months of the year */ + { // Months of the year "Jan", "Feb", "Mar", @@ -79,97 +58,64 @@ static const char * const http_months[12] = "Dec" }; static const char * const http_states[] = - { /* HTTP state strings */ - "HTTP_STATE_ERROR", - "HTTP_STATE_WAITING", - "HTTP_STATE_OPTIONS", - "HTTP_STATE_GET", - "HTTP_STATE_GET_SEND", - "HTTP_STATE_HEAD", - "HTTP_STATE_POST", - "HTTP_STATE_POST_RECV", - "HTTP_STATE_POST_SEND", - "HTTP_STATE_PUT", - "HTTP_STATE_PUT_RECV", - "HTTP_STATE_DELETE", - "HTTP_STATE_TRACE", - "HTTP_STATE_CONNECT", - "HTTP_STATE_STATUS", - "HTTP_STATE_UNKNOWN_METHOD", - "HTTP_STATE_UNKNOWN_VERSION" + { // HTTP state strings + "ERROR", + "WAITING", + "OPTIONS", + "GET", + "GET-send", + "HEAD", + "POST", + "POST-recv", + "POST-send", + "PUT", + "PUT-recv", + "DELETE", + "TRACE", + "CONNECT", + "STATUS", + "UNKNOWN_METHOD", + "UNKNOWN_VERSION" }; -/* - * Local functions... - */ - -static const char *http_copy_decode(char *dst, const char *src, - int dstsize, const char *term, - int decode); -static char *http_copy_encode(char *dst, const char *src, - char *dstend, const char *reserved, - const char *term, int encode); -#ifdef HAVE_MDNSRESPONDER -static void DNSSD_API http_resolve_cb(DNSServiceRef sdRef, - DNSServiceFlags flags, - uint32_t interfaceIndex, - DNSServiceErrorType errorCode, - const char *fullName, - const char *hostTarget, - uint16_t port, uint16_t txtLen, - const unsigned char *txtRecord, - void *context); -#endif /* HAVE_MDNSRESPONDER */ - -#ifdef HAVE_AVAHI -static void http_client_cb(AvahiClient *client, - AvahiClientState state, void *simple_poll); -static int http_poll_cb(struct pollfd *pollfds, unsigned int num_pollfds, - int timeout, void *context); -static void http_resolve_cb(AvahiServiceResolver *resolver, - AvahiIfIndex interface, - AvahiProtocol protocol, - AvahiResolverEvent event, - const char *name, const char *type, - const char *domain, const char *host_name, - const AvahiAddress *address, uint16_t port, - AvahiStringList *txt, - AvahiLookupResultFlags flags, void *context); -#endif /* HAVE_AVAHI */ - - -/* - * 'httpAssembleURI()' - Assemble a uniform resource identifier from its - * components. - * - * This function escapes reserved characters in the URI depending on the - * value of the "encoding" argument. You should use this function in - * place of traditional string functions whenever you need to create a - * URI string. - * - * @since CUPS 1.2/macOS 10.5@ - */ - -http_uri_status_t /* O - URI status */ +// +// Local functions... +// + +static const char *http_copy_decode(char *dst, const char *src, size_t dstsize, const char *term, int decode); +static char *http_copy_encode(char *dst, const char *src, char *dstend, const char *reserved, const char *term, int encode); +static void http_resolve_cb(cups_dnssd_resolve_t *res, void *cb_data, cups_dnssd_flags_t flags, uint32_t if_index, const char *fullname, const char *host, uint16_t port, size_t num_txt, cups_option_t *txt); + + +// +// 'httpAssembleURI()' - Assemble a uniform resource identifier from its +// components. +// +// This function escapes reserved characters in the URI depending on the +// value of the "encoding" argument. You should use this function in +// place of traditional string functions whenever you need to create a +// URI string. +// +// @since CUPS 1.2/macOS 10.5@ +// + +http_uri_status_t // O - URI status httpAssembleURI( - http_uri_coding_t encoding, /* I - Encoding flags */ - char *uri, /* I - URI buffer */ - int urilen, /* I - Size of URI buffer */ - const char *scheme, /* I - Scheme name */ - const char *username, /* I - Username */ - const char *host, /* I - Hostname or address */ - int port, /* I - Port number */ - const char *resource) /* I - Resource */ + http_uri_coding_t encoding, // I - Encoding flags + char *uri, // I - URI buffer + int urilen, // I - Size of URI buffer + const char *scheme, // I - Scheme name + const char *username, // I - Username + const char *host, // I - Hostname or address + int port, // I - Port number + const char *resource) // I - Resource { - char *ptr, /* Pointer into URI buffer */ - *end; /* End of URI buffer */ + char *ptr, // Pointer into URI buffer + *end; // End of URI buffer - /* - * Range check input... - */ - + // Range check input... if (!uri || urilen < 1 || !scheme || port < 0) { if (uri) @@ -178,10 +124,7 @@ httpAssembleURI( return (HTTP_URI_STATUS_BAD_ARGUMENTS); } - /* - * Assemble the URI starting with the scheme... - */ - + // Assemble the URI starting with the scheme... end = uri + urilen - 1; ptr = http_copy_encode(uri, scheme, end, NULL, NULL, 0); @@ -190,10 +133,7 @@ httpAssembleURI( if (!strcmp(scheme, "geo") || !strcmp(scheme, "mailto") || !strcmp(scheme, "tel")) { - /* - * geo:, mailto:, and tel: only have :, no //... - */ - + // geo:, mailto:, and tel: only have :, no //... if (ptr < end) *ptr++ = ':'; else @@ -201,10 +141,7 @@ httpAssembleURI( } else { - /* - * Schemes other than geo:, mailto:, and tel: typically have //... - */ - + // Schemes other than geo:, mailto:, and tel: typically have //... if ((ptr + 2) < end) { *ptr++ = ':'; @@ -212,26 +149,21 @@ httpAssembleURI( *ptr++ = '/'; } else + { goto assemble_overflow; + } } - /* - * Next the username and hostname, if any... - */ - + // Next the username and hostname, if any... if (host) { - const char *hostptr; /* Pointer into hostname */ - int have_ipv6; /* Do we have an IPv6 address? */ + const char *hostptr; // Pointer into hostname + int have_ipv6; // Do we have an IPv6 address? if (username && *username) { - /* - * Add username@ first... - */ - - ptr = http_copy_encode(ptr, username, end, "/?#[]@", NULL, - encoding & HTTP_URI_CODING_USERNAME); + // Add username@ first... + ptr = http_copy_encode(ptr, username, end, "/?#[]@", NULL, encoding & HTTP_URI_CODING_USERNAME); if (!ptr) goto assemble_overflow; @@ -242,37 +174,27 @@ httpAssembleURI( goto assemble_overflow; } - /* - * Then add the hostname. Since IPv6 is a particular pain to deal - * with, we have several special cases to deal with. If we get - * an IPv6 address with brackets around it, assume it is already in - * URI format. Since DNS-SD service names can sometimes look like - * raw IPv6 addresses, we specifically look for "._tcp" in the name, - * too... - */ - - for (hostptr = host, - have_ipv6 = strchr(host, ':') && !strstr(host, "._tcp"); - *hostptr && have_ipv6; - hostptr ++) + // Then add the hostname. Since IPv6 is a particular pain to deal + // with, we have several special cases to deal with. If we get + // an IPv6 address with brackets around it, assume it is already in + // URI format. Since DNS-SD service names can sometimes look like + // raw IPv6 addresses, we specifically look for "._tcp" in the name, + // too... + for (hostptr = host, have_ipv6 = strchr(host, ':') && !strstr(host, "._tcp"); *hostptr && have_ipv6; hostptr ++) + { if (*hostptr != ':' && !isxdigit(*hostptr & 255)) { have_ipv6 = *hostptr == '%'; break; } + } if (have_ipv6) { - /* - * We have a raw IPv6 address... - */ - + // We have a raw IPv6 address... if (strchr(host, '%') && !(encoding & HTTP_URI_CODING_RFC6874)) { - /* - * We have a link-local address, add "[v1." prefix... - */ - + // We have a link-local address, add "[v1." prefix... if ((ptr + 4) < end) { *ptr++ = '['; @@ -281,32 +203,25 @@ httpAssembleURI( *ptr++ = '.'; } else + { goto assemble_overflow; + } } else { - /* - * We have a normal (or RFC 6874 link-local) address, add "[" prefix... - */ - + // We have a normal (or RFC 6874 link-local) address, add "[" prefix... if (ptr < end) *ptr++ = '['; else goto assemble_overflow; } - /* - * Copy the rest of the IPv6 address, and terminate with "]". - */ - + // Copy the rest of the IPv6 address, and terminate with "]". while (ptr < end && *host) { if (*host == '%') { - /* - * Convert/encode zone separator - */ - + // Convert/encode zone separator if (encoding & HTTP_URI_CODING_RFC6874) { if (ptr >= (end - 2)) @@ -317,12 +232,16 @@ httpAssembleURI( *ptr++ = '5'; } else + { *ptr++ = '+'; + } host ++; } else + { *ptr++ = *host++; + } } if (*host) @@ -335,23 +254,16 @@ httpAssembleURI( } else { - /* - * Otherwise, just copy the host string (the extra chars are not in the - * "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically - * percent-encoded. - */ - - ptr = http_copy_encode(ptr, host, end, "\"#/:<>?@[\\]^`{|}", NULL, - encoding & HTTP_URI_CODING_HOSTNAME); + // Otherwise, just copy the host string (the extra chars are not in the + // "reg-name" ABNF rule; anything <= SP or >= DEL plus % gets automatically + // percent-encoded. + ptr = http_copy_encode(ptr, host, end, "\"#/:<>?@[\\]^`{|}", NULL, encoding & HTTP_URI_CODING_HOSTNAME); if (!ptr) goto assemble_overflow; } - /* - * Finish things off with the port number... - */ - + // Finish things off with the port number... if (port > 0) { snprintf(ptr, (size_t)(end - ptr + 1), ":%d", port); @@ -362,55 +274,41 @@ httpAssembleURI( } } - /* - * Last but not least, add the resource string... - */ - + // Last but not least, add the resource string... if (resource) { - char *query; /* Pointer to query string */ - - - /* - * Copy the resource string up to the query string if present... - */ + char *query; // Pointer to query string + // Copy the resource string up to the query string if present... query = strchr(resource, '?'); - ptr = http_copy_encode(ptr, resource, end, NULL, "?", - encoding & HTTP_URI_CODING_RESOURCE); + ptr = http_copy_encode(ptr, resource, end, NULL, "?", encoding & HTTP_URI_CODING_RESOURCE); if (!ptr) goto assemble_overflow; if (query) { - /* - * Copy query string without encoding... - */ - - ptr = http_copy_encode(ptr, query, end, NULL, NULL, - encoding & HTTP_URI_CODING_QUERY); + // Copy query string without encoding... + ptr = http_copy_encode(ptr, query, end, NULL, NULL, encoding & HTTP_URI_CODING_QUERY); if (!ptr) goto assemble_overflow; } } else if (ptr < end) + { *ptr++ = '/'; + } else + { goto assemble_overflow; + } - /* - * Nul-terminate the URI buffer and return with no errors... - */ - + // Nul-terminate the URI buffer and return with no errors... *ptr = '\0'; return (HTTP_URI_STATUS_OK); - /* - * Clear the URI string and return an overflow error; I don't usually - * like goto's, but in this case it makes sense... - */ - + // Clear the URI string and return an overflow error; I don't usually + // like goto's, but in this case it makes sense... assemble_overflow: *uri = '\0'; @@ -418,40 +316,36 @@ httpAssembleURI( } -/* - * 'httpAssembleURIf()' - Assemble a uniform resource identifier from its - * components with a formatted resource. - * - * This function creates a formatted version of the resource string - * argument "resourcef" and escapes reserved characters in the URI - * depending on the value of the "encoding" argument. You should use - * this function in place of traditional string functions whenever - * you need to create a URI string. - * - * @since CUPS 1.2/macOS 10.5@ - */ - -http_uri_status_t /* O - URI status */ +// +// 'httpAssembleURIf()' - Assemble a uniform resource identifier from its components with a formatted resource. +// +// This function creates a formatted version of the resource string +// argument "resourcef" and escapes reserved characters in the URI +// depending on the value of the "encoding" argument. You should use +// this function in place of traditional string functions whenever +// you need to create a URI string. +// +// @since CUPS 1.2/macOS 10.5@ +// + +http_uri_status_t // O - URI status httpAssembleURIf( - http_uri_coding_t encoding, /* I - Encoding flags */ - char *uri, /* I - URI buffer */ - int urilen, /* I - Size of URI buffer */ - const char *scheme, /* I - Scheme name */ - const char *username, /* I - Username */ - const char *host, /* I - Hostname or address */ - int port, /* I - Port number */ - const char *resourcef, /* I - Printf-style resource */ - ...) /* I - Additional arguments as needed */ + http_uri_coding_t encoding, // I - Encoding flags + char *uri, // I - URI buffer + int urilen, // I - Size of URI buffer + const char *scheme, // I - Scheme name + const char *username, // I - Username + const char *host, // I - Hostname or address + int port, // I - Port number + const char *resourcef, // I - Printf-style resource + ...) // I - Additional arguments as needed { - va_list ap; /* Pointer to additional arguments */ - char resource[1024]; /* Formatted resource string */ - int bytes; /* Bytes in formatted string */ + va_list ap; // Pointer to additional arguments + char resource[1024]; // Formatted resource string + int bytes; // Bytes in formatted string - /* - * Range check input... - */ - + // Range check input... if (!uri || urilen < 1 || !scheme || port < 0 || !resourcef) { if (uri) @@ -460,10 +354,7 @@ httpAssembleURIf( return (HTTP_URI_STATUS_BAD_ARGUMENTS); } - /* - * Format the resource string and assemble the URI... - */ - + // Format the resource string and assemble the URI... va_start(ap, resourcef); bytes = vsnprintf(resource, sizeof(resource), resourcef, ap); va_end(ap); @@ -474,115 +365,140 @@ httpAssembleURIf( return (HTTP_URI_STATUS_OVERFLOW); } else - return (httpAssembleURI(encoding, uri, urilen, scheme, username, host, - port, resource)); + { + return (httpAssembleURI(encoding, uri, urilen, scheme, username, host, port, resource)); + } } -/* - * 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122. - * - * This function creates a unique 128-bit identifying number using the server - * name, port number, random data, and optionally an object name and/or object - * number. The result is formatted as a UUID URN as defined in RFC 4122. - * - * The buffer needs to be at least 46 bytes in size. - * - * @since CUPS 1.7/macOS 10.9@ - */ - -char * /* I - UUID string */ -httpAssembleUUID(const char *server, /* I - Server name */ - int port, /* I - Port number */ - const char *name, /* I - Object name or NULL */ - int number, /* I - Object number or 0 */ - char *buffer, /* I - String buffer */ - size_t bufsize) /* I - Size of buffer */ +// +// 'httpAssembleUUID()' - Assemble a name-based UUID URN conforming to RFC 4122. +// +// This function creates a unique 128-bit identifying number using the server +// name, port number, random data, and optionally an object name and/or object +// number. The result is formatted as a UUID URN as defined in RFC 4122. +// +// The buffer needs to be at least 46 bytes in size. +// +// @since CUPS 1.7/macOS 10.9@ +// + +char * // I - UUID string +httpAssembleUUID(const char *server, // I - Server name + int port, // I - Port number + const char *name, // I - Object name or NULL + int number, // I - Object number or 0 + char *buffer, // I - String buffer + size_t bufsize) // I - Size of buffer { - char data[1024]; /* Source string for MD5 */ - unsigned char md5sum[16]; /* MD5 digest/sum */ - + char data[1024]; // Source string for MD5 + unsigned char md5sum[16]; // MD5 digest/sum - /* - * Build a version 3 UUID conforming to RFC 4122. - * - * Start with the MD5 sum of the server, port, object name and - * number, and some random data on the end. - */ - snprintf(data, sizeof(data), "%s:%d:%s:%d:%04x:%04x", server, - port, name ? name : server, number, - (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff); + // Build a version 3 UUID conforming to RFC 4122. + // + // Start with the MD5 sum of the server, port, object name and + // number, and some random data on the end. + snprintf(data, sizeof(data), "%s:%d:%s:%d:%04x:%04x", server, port, name ? name : server, number, (unsigned)CUPS_RAND() & 0xffff, (unsigned)CUPS_RAND() & 0xffff); cupsHashData("md5", (unsigned char *)data, strlen(data), md5sum, sizeof(md5sum)); - /* - * Generate the UUID from the MD5... - */ - - snprintf(buffer, bufsize, - "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-" - "%02x%02x%02x%02x%02x%02x", - md5sum[0], md5sum[1], md5sum[2], md5sum[3], md5sum[4], md5sum[5], - (md5sum[6] & 15) | 0x30, md5sum[7], (md5sum[8] & 0x3f) | 0x40, - md5sum[9], md5sum[10], md5sum[11], md5sum[12], md5sum[13], - md5sum[14], md5sum[15]); + // Generate the UUID from the MD5... + snprintf(buffer, bufsize, "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", md5sum[0], md5sum[1], md5sum[2], md5sum[3], md5sum[4], md5sum[5], (md5sum[6] & 15) | 0x30, md5sum[7], (md5sum[8] & 0x3f) | 0x40, md5sum[9], md5sum[10], md5sum[11], md5sum[12], md5sum[13], md5sum[14], md5sum[15]); return (buffer); } -/* - * 'httpDecode64()' - Base64-decode a string. - * - * This function is deprecated. Use the httpDecode64_2() function instead - * which provides buffer length arguments. - * - * @deprecated@ @exclude all@ - */ +// +// 'httpDecode64()' - Base64-decode a string. +// +// This function is deprecated. Use the httpDecode64_2() function instead +// which provides buffer length arguments. +// +// @deprecated@ @exclude all@ +// -char * /* O - Decoded string */ -httpDecode64(char *out, /* I - String to write to */ - const char *in) /* I - String to read from */ +char * // O - Decoded string +httpDecode64(char *out, // I - String to write to + const char *in) // I - String to read from { - int outlen; /* Output buffer length */ + size_t outlen; // Output buffer length - /* - * Use the old maximum buffer size for binary compatibility... - */ - + // Use the old maximum buffer size for binary compatibility... outlen = 512; - return (httpDecode64_2(out, &outlen, in)); + return (httpDecode64_3(out, &outlen, in, NULL)); } -/* - * 'httpDecode64_2()' - Base64-decode a string. - * - * The caller must initialize "outlen" to the maximum size of the decoded - * string before calling @code httpDecode64_2@. On return "outlen" contains the - * decoded length of the string. - * - * @since CUPS 1.1.21/macOS 10.4@ - */ - -char * /* O - Decoded string */ -httpDecode64_2(char *out, /* I - String to write to */ - int *outlen, /* IO - Size of output string */ - const char *in) /* I - String to read from */ +// +// 'httpDecode64_2()' - Base64-decode a string. +// +// The caller must initialize "outlen" to the maximum size of the decoded +// string before calling @code httpDecode64_2@. On return "outlen" contains the +// decoded length of the string. +// +// @deprecsted@ @exclude all@ +// + +char * // O - Decoded string +httpDecode64_2(char *out, // I - String to write to + int *outlen, // IO - Size of output string + const char *in) // I - String to read from { - int pos; /* Bit position */ - unsigned base64; /* Value of this character */ - char *outptr, /* Output pointer */ - *outend; /* End of output buffer */ + size_t templen; // Temporary length + char *ret; // Return value - /* - * Range check input... - */ + // Range check input... + if (!outlen || *outlen < 1) + return (NULL); + + // Decode... + templen = (size_t)*outlen; + ret = httpDecode64_3(out, &templen, in, NULL); + // Save return values... + *outlen = (int)templen; + + return (ret); +} + + +// +// 'httpDecode64_3()' - Base64-decode a string. +// +// This function decodes a Base64 string as defined by RFC 4648. The caller +// must initialize "outlen" to the maximum size of the decoded string. On +// return "outlen" contains the decoded length of the string and "end" (if not +// `NULL`) points to the end of the Base64 data that has been decoded. +// +// This function always reserves one byte in the output buffer for a nul +// terminating character, even if the result is not a regular string. Callers +// should ensure that the output buffer is at least one byte larger than the +// expected size, for example 33 bytes for a SHA-256 hash which is 32 bytes in +// length. +// +// This function supports both Base64 and Base64url strings. +// +// @since CUPS 2.5@ +// + +char * // O - Decoded string or `NULL` on error +httpDecode64_3(char *out, // I - String to write to + size_t *outlen, // IO - Size of output string + const char *in, // I - String to read from + const char **end) // O - Pointer to end of Base64 data (`NULL` if don't care) +{ + int pos; // Bit position + unsigned base64; // Value of this character + char *outptr, // Output pointer + *outend; // End of output buffer + + + // Range check input... if (!out || !outlen || *outlen < 1 || !in) return (NULL); @@ -591,38 +507,34 @@ httpDecode64_2(char *out, /* I - String to write to */ *out = '\0'; *outlen = 0; + if (end) + *end = in; + return (out); } - /* - * Convert from base-64 to bytes... - */ - + // Convert from base-64 to bytes... for (outptr = out, outend = out + *outlen - 1, pos = 0; *in != '\0'; in ++) { - /* - * Decode this character into a number from 0 to 63... - */ - + // Decode this character into a number from 0 to 63... if (*in >= 'A' && *in <= 'Z') base64 = (unsigned)(*in - 'A'); else if (*in >= 'a' && *in <= 'z') base64 = (unsigned)(*in - 'a' + 26); else if (*in >= '0' && *in <= '9') base64 = (unsigned)(*in - '0' + 52); - else if (*in == '+') + else if (*in == '+' || *in == '-') base64 = 62; - else if (*in == '/') + else if (*in == '/' || *in == '_') base64 = 63; else if (*in == '=') break; - else + else if (isspace(*in & 255)) continue; + else + break; - /* - * Store the result in the appropriate chars... - */ - + // Store the result in the appropriate chars... switch (pos) { case 0 : @@ -652,156 +564,170 @@ httpDecode64_2(char *out, /* I - String to write to */ } } + // Add a trailing nul... *outptr = '\0'; - /* - * Return the decoded string and size... - */ + // Skip trailing '='... + while (*in == '=') + in ++; + + // Return the decoded string, next input pointer, and size... + *outlen = (size_t)(outptr - out); - *outlen = (int)(outptr - out); + if (end) + *end = in; return (out); } -/* - * 'httpEncode64()' - Base64-encode a string. - * - * This function is deprecated. Use the httpEncode64_2() function instead - * which provides buffer length arguments. - * - * @deprecated@ @exclude all@ - */ +// +// 'httpEncode64()' - Base64-encode a string. +// +// This function is deprecated. Use the httpEncode64_2() function instead +// which provides buffer length arguments. +// +// @deprecated@ @exclude all@ +// -char * /* O - Encoded string */ -httpEncode64(char *out, /* I - String to write to */ - const char *in) /* I - String to read from */ +char * // O - Encoded string +httpEncode64(char *out, // I - String to write to + const char *in) // I - String to read from { return (httpEncode64_2(out, 512, in, (int)strlen(in))); } -/* - * 'httpEncode64_2()' - Base64-encode a string. - * - * @since CUPS 1.1.21/macOS 10.4@ - */ +// +// 'httpEncode64_2()' - Base64-encode a string. +// +// @deprecated@ @exclude all@ +// -char * /* O - Encoded string */ -httpEncode64_2(char *out, /* I - String to write to */ - int outlen, /* I - Maximum size of output string */ - const char *in, /* I - String to read from */ - int inlen) /* I - Size of input string */ +char * // O - Encoded string +httpEncode64_2(char *out, // I - String to write to + int outlen, // I - Maximum size of output string + const char *in, // I - String to read from + int inlen) // I - Size of input string { - char *outptr, /* Output pointer */ - *outend; /* End of output buffer */ - static const char base64[] = /* Base64 characters... */ - { - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789" - "+/" - }; + return (httpEncode64_3(out, outlen, in, inlen, false)); +} - /* - * Range check input... - */ +// +// 'httpEncode64_3()' - Base64-encode a string. +// +// This function encodes a Base64 string as defined by RFC 4648. The "url" +// parameter controls whether the original Base64 ("url" = `false`) or the +// Base64url ("url" = `true`) alphabet is used. +// +// @since CUPS 2.5@ +// + +char * // O - Encoded string +httpEncode64_3(char *out, // I - String to write to + size_t outlen, // I - Maximum size of output string + const char *in, // I - String to read from + size_t inlen, // I - Size of input string + bool url) // I - `true` for Base64url, `false` for Base64 +{ + char *outptr, // Output pointer + *outend; // End of output buffer + const char *alpha; // Alphabet + static const char *base64 = // Base64 alphabet + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + static const char *base64url = // Base64url alphabet + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + // Range check input... if (!out || outlen < 1 || !in) return (NULL); - /* - * Convert bytes to base-64... - */ + // Encode bytes... + alpha = url ? base64url : base64; for (outptr = out, outend = out + outlen - 1; inlen > 0; in ++, inlen --) { - /* - * Encode the up to 3 characters as 4 Base64 numbers... - */ - + // Encode the up to 3 characters as 4 Base64 numbers... if (outptr < outend) - *outptr ++ = base64[(in[0] & 255) >> 2]; + *outptr ++ = alpha[(in[0] & 255) >> 2]; if (outptr < outend) { if (inlen > 1) - *outptr ++ = base64[(((in[0] & 255) << 4) | ((in[1] & 255) >> 4)) & 63]; + *outptr ++ = alpha[(((in[0] & 255) << 4) | ((in[1] & 255) >> 4)) & 63]; else - *outptr ++ = base64[(in[0] << 4) & 63]; + *outptr ++ = alpha[((in[0] & 255) << 4) & 63]; } in ++; inlen --; if (inlen <= 0) { - if (outptr < outend) - *outptr ++ = '='; - if (outptr < outend) - *outptr ++ = '='; + if (!url && outptr < outend) + *outptr ++ = '='; + if (!url && outptr < outend) + *outptr ++ = '='; break; } if (outptr < outend) { if (inlen > 1) - *outptr ++ = base64[(((in[0] & 255) << 2) | ((in[1] & 255) >> 6)) & 63]; + *outptr ++ = alpha[(((in[0] & 255) << 2) | ((in[1] & 255) >> 6)) & 63]; else - *outptr ++ = base64[(in[0] << 2) & 63]; + *outptr ++ = alpha[((in[0] & 255) << 2) & 63]; } in ++; inlen --; if (inlen <= 0) { - if (outptr < outend) + if (!url && outptr < outend) *outptr ++ = '='; break; } if (outptr < outend) - *outptr ++ = base64[in[0] & 63]; + *outptr ++ = alpha[in[0] & 63]; } *outptr = '\0'; - /* - * Return the encoded string... - */ - + // Return the encoded string... return (out); } -/* - * 'httpGetDateString()' - Get a formatted date/time string from a time value. - * - * @deprecated@ @exclude all@ - */ +// +// 'httpGetDateString()' - Get a formatted date/time string from a time value. +// +// @deprecated@ @exclude all@ +// -const char * /* O - Date/time string */ -httpGetDateString(time_t t) /* I - Time in seconds */ +const char * // O - Date/time string +httpGetDateString(time_t t) // I - Time in seconds { - _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */ + _cups_globals_t *cg = _cupsGlobals(); // Pointer to library globals return (httpGetDateString2(t, cg->http_date, sizeof(cg->http_date))); } -/* - * 'httpGetDateString2()' - Get a formatted date/time string from a time value. - * - * @since CUPS 1.2/macOS 10.5@ - */ +// +// 'httpGetDateString2()' - Get a formatted date/time string from a time value. +// +// @since CUPS 1.2/macOS 10.5@ +// -const char * /* O - Date/time string */ -httpGetDateString2(time_t t, /* I - Time in seconds */ - char *s, /* I - String buffer */ - int slen) /* I - Size of string buffer */ +const char * // O - Date/time string +httpGetDateString2(time_t t, // I - Time in seconds + char *s, // I - String buffer + int slen) // I - Size of string buffer { - struct tm tdate; /* UNIX date/time data */ + struct tm tdate; // UNIX date/time data gmtime_r(&t, &tdate); @@ -812,62 +738,51 @@ httpGetDateString2(time_t t, /* I - Time in seconds */ } -/* - * 'httpGetDateTime()' - Get a time value from a formatted date/time string. - */ +// +// 'httpGetDateTime()' - Get a time value from a formatted date/time string. +// -time_t /* O - Time in seconds */ -httpGetDateTime(const char *s) /* I - Date/time string */ +time_t // O - Time in seconds +httpGetDateTime(const char *s) // I - Date/time string { - int i; /* Looping var */ - char mon[16]; /* Abbreviated month name */ - int day, year; /* Day of month and year */ - int hour, min, sec; /* Time */ - int days; /* Number of days since 1970 */ - static const int normal_days[] = /* Days to a month, normal years */ + int i; // Looping var + char mon[16]; // Abbreviated month name + int day, year; // Day of month and year + int hour, min, sec; // Time + int days; // Number of days since 1970 + static const int normal_days[] = // Days to a month, normal years { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; - static const int leap_days[] = /* Days to a month, leap years */ + static const int leap_days[] = // Days to a month, leap years { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; DEBUG_printf("2httpGetDateTime(s=\"%s\")", s); - /* - * Extract the date and time from the formatted string... - */ - + // Extract the date and time from the formatted string... if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6) return (0); - DEBUG_printf(("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, " - "min=%d, sec=%d", day, mon, year, hour, min, sec)); - - /* - * Check for invalid year (RFC 7231 says it's 4DIGIT) - */ + DEBUG_printf("4httpGetDateTime: day=%d, mon=\"%s\", year=%d, hour=%d, min=%d, sec=%d", day, mon, year, hour, min, sec); + // Check for invalid year (RFC 7231 says it's 4DIGIT) if (year > 9999) return (0); - /* - * Convert the month name to a number from 0 to 11. - */ - + // Convert the month name to a number from 0 to 11. for (i = 0; i < 12; i ++) + { if (!_cups_strcasecmp(mon, http_months[i])) break; + } if (i >= 12) return (0); DEBUG_printf("4httpGetDateTime: i=%d", i); - /* - * Now convert the date and time to a UNIX time value in seconds since - * 1970. We can't use mktime() since the timezone may not be UTC but - * the date/time string *is* UTC. - */ - + // Now convert the date and time to a UNIX time value in seconds since + // 1970. We can't use mktime() since the timezone may not be UTC but + // the date/time string *is* UTC. if ((year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0)) days = leap_days[i] + day - 1; else @@ -875,10 +790,10 @@ httpGetDateTime(const char *s) /* I - Date/time string */ DEBUG_printf("4httpGetDateTime: days=%d", days); - days += (year - 1970) * 365 + /* 365 days per year (normally) */ - ((year - 1) / 4 - 492) - /* + leap days */ - ((year - 1) / 100 - 19) + /* - 100 year days */ - ((year - 1) / 400 - 4); /* + 400 year days */ + days += (year - 1970) * 365 + // 365 days per year (normally) + ((year - 1) / 4 - 492) - // + leap days + ((year - 1) / 100 - 19) + // - 100 year days + ((year - 1) / 400 - 4); // + 400 year days DEBUG_printf("4httpGetDateTime: days=%d\n", days); @@ -886,87 +801,80 @@ httpGetDateTime(const char *s) /* I - Date/time string */ } -/* - * 'httpSeparate()' - Separate a Universal Resource Identifier into its - * components. - * - * This function is deprecated; use the httpSeparateURI() function instead. - * - * @deprecated@ @exclude all@ - */ +// +// 'httpSeparate()' - Separate a Universal Resource Identifier into its +// components. +// +// This function is deprecated; use the httpSeparateURI() function instead. +// +// @deprecated@ @exclude all@ +// void -httpSeparate(const char *uri, /* I - Universal Resource Identifier */ - char *scheme, /* O - Scheme [32] (http, https, etc.) */ - char *username, /* O - Username [1024] */ - char *host, /* O - Hostname [1024] */ - int *port, /* O - Port number to use */ - char *resource) /* O - Resource/filename [1024] */ +httpSeparate(const char *uri, // I - Universal Resource Identifier + char *scheme, // O - Scheme [32] (http, https, etc.) + char *username, // O - Username [1024] + char *host, // O - Hostname [1024] + int *port, // O - Port number to use + char *resource) // O - Resource/filename [1024] { - httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, 32, username, - HTTP_MAX_URI, host, HTTP_MAX_URI, port, resource, - HTTP_MAX_URI); + httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, 32, username, HTTP_MAX_URI, host, HTTP_MAX_URI, port, resource, HTTP_MAX_URI); } -/* - * 'httpSeparate2()' - Separate a Universal Resource Identifier into its - * components. - * - * This function is deprecated; use the httpSeparateURI() function instead. - * - * @since CUPS 1.1.21/macOS 10.4@ - * @deprecated@ @exclude all@ - */ +// +// 'httpSeparate2()' - Separate a Universal Resource Identifier into its +// components. +// +// This function is deprecated; use the httpSeparateURI() function instead. +// +// @deprecated@ @exclude all@ +// void -httpSeparate2(const char *uri, /* I - Universal Resource Identifier */ - char *scheme, /* O - Scheme (http, https, etc.) */ - int schemelen, /* I - Size of scheme buffer */ - char *username, /* O - Username */ - int usernamelen, /* I - Size of username buffer */ - char *host, /* O - Hostname */ - int hostlen, /* I - Size of hostname buffer */ - int *port, /* O - Port number to use */ - char *resource, /* O - Resource/filename */ - int resourcelen) /* I - Size of resource buffer */ +httpSeparate2(const char *uri, // I - Universal Resource Identifier + char *scheme, // O - Scheme (http, https, etc.) + int schemelen, // I - Size of scheme buffer + char *username, // O - Username + int usernamelen, // I - Size of username buffer + char *host, // O - Hostname + int hostlen, // I - Size of hostname buffer + int *port, // O - Port number to use + char *resource, // O - Resource/filename + int resourcelen) // I - Size of resource buffer { - httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, schemelen, username, - usernamelen, host, hostlen, port, resource, resourcelen); + httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, schemelen, username, usernamelen, host, hostlen, port, resource, resourcelen); } -/* - * 'httpSeparateURI()' - Separate a Universal Resource Identifier into its - * components. - * - * @since CUPS 1.2/macOS 10.5@ - */ +// +// 'httpSeparateURI()' - Separate a Universal Resource Identifier into its +// components. +// +// @since CUPS 1.2/macOS 10.5@ +// -http_uri_status_t /* O - Result of separation */ +http_uri_status_t // O - Result of separation httpSeparateURI( - http_uri_coding_t decoding, /* I - Decoding flags */ - const char *uri, /* I - Universal Resource Identifier */ - char *scheme, /* O - Scheme (http, https, etc.) */ - int schemelen, /* I - Size of scheme buffer */ - char *username, /* O - Username */ - int usernamelen, /* I - Size of username buffer */ - char *host, /* O - Hostname */ - int hostlen, /* I - Size of hostname buffer */ - int *port, /* O - Port number to use */ - char *resource, /* O - Resource/filename */ - int resourcelen) /* I - Size of resource buffer */ + http_uri_coding_t decoding, // I - Decoding flags + const char *uri, // I - Universal Resource Identifier + char *scheme, // O - Scheme (http, https, etc.) + int schemelen, // I - Size of scheme buffer + char *username, // O - Username + int usernamelen, // I - Size of username buffer + char *host, // O - Hostname + int hostlen, // I - Size of hostname buffer + int *port, // O - Port number to use + char *resource, // O - Resource/filename + int resourcelen) // I - Size of resource buffer { - char *ptr, /* Pointer into string... */ - *end; /* End of string */ - const char *sep; /* Separator character */ - http_uri_status_t status; /* Result of separation */ - + char *ptr, // Pointer into string... + *end; // End of string + const char *sep; // Separator character + http_uri_status_t status; // Result of separation - /* - * Initialize everything to blank... - */ + // Initialize everything to blank... if (scheme && schemelen > 0) *scheme = '\0'; @@ -982,56 +890,40 @@ httpSeparateURI( if (resource && resourcelen > 0) *resource = '\0'; - /* - * Range check input... - */ - - if (!uri || !port || !scheme || schemelen <= 0 || !username || - usernamelen <= 0 || !host || hostlen <= 0 || !resource || - resourcelen <= 0) + // Range check input... + if (!uri || !port || !scheme || schemelen <= 0 || !username || usernamelen <= 0 || !host || hostlen <= 0 || !resource || resourcelen <= 0) return (HTTP_URI_STATUS_BAD_ARGUMENTS); if (!*uri) return (HTTP_URI_STATUS_BAD_URI); - /* - * Grab the scheme portion of the URI... - */ - + // Grab the scheme portion of the URI... status = HTTP_URI_STATUS_OK; if (!strncmp(uri, "//", 2)) { - /* - * Workaround for HP IPP client bug... - */ - + // Workaround for HP IPP client bug... strlcpy(scheme, "ipp", (size_t)schemelen); status = HTTP_URI_STATUS_MISSING_SCHEME; } else if (*uri == '/') { - /* - * Filename... - */ - + // Filename... strlcpy(scheme, "file", (size_t)schemelen); status = HTTP_URI_STATUS_MISSING_SCHEME; } else { - /* - * Standard URI with scheme... - */ - - for (ptr = scheme, end = scheme + schemelen - 1; - *uri && *uri != ':' && ptr < end;) + // Standard URI with scheme... + for (ptr = scheme, end = scheme + schemelen - 1; *uri && *uri != ':' && ptr < end;) + { if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789-+.", *uri) != NULL) *ptr++ = *uri++; else break; + } *ptr = '\0'; @@ -1044,10 +936,7 @@ httpSeparateURI( uri ++; } - /* - * Set the default port number... - */ - + // Set the default port number... if (!strcmp(scheme, "http")) *port = 80; else if (!strcmp(scheme, "https")) @@ -1056,35 +945,22 @@ httpSeparateURI( *port = 631; else if (!_cups_strcasecmp(scheme, "lpd")) *port = 515; - else if (!strcmp(scheme, "socket")) /* Not yet registered with IANA... */ + else if (!strcmp(scheme, "socket")) // Not yet registered with IANA... *port = 9100; else if (strcmp(scheme, "file") && strcmp(scheme, "mailto") && strcmp(scheme, "tel")) status = HTTP_URI_STATUS_UNKNOWN_SCHEME; - /* - * Now see if we have a hostname... - */ - + // Now see if we have a hostname... if (!strncmp(uri, "//", 2)) { - /* - * Yes, extract it... - */ - + // Yes, extract it... uri += 2; - /* - * Grab the username, if any... - */ - + // Grab the username, if any... if ((sep = strpbrk(uri, "@/")) != NULL && *sep == '@') { - /* - * Get a username:password combo... - */ - - uri = http_copy_decode(username, uri, usernamelen, "@", - decoding & HTTP_URI_CODING_USERNAME); + // Get a username:password combo... + uri = http_copy_decode(username, uri, usernamelen, "@", decoding & HTTP_URI_CODING_USERNAME); if (!uri) { @@ -1095,23 +971,14 @@ httpSeparateURI( uri ++; } - /* - * Then the hostname/IP address... - */ - + // Then the hostname/IP address... if (*uri == '[') { - /* - * Grab IPv6 address... - */ - + // Grab IPv6 address... uri ++; if (*uri == 'v') { - /* - * Skip IPvFuture ("vXXXX.") prefix... - */ - + // Skip IPvFuture ("vXXXX.") prefix... uri ++; while (isxdigit(*uri & 255)) @@ -1126,8 +993,7 @@ httpSeparateURI( uri ++; } - uri = http_copy_decode(host, uri, hostlen, "]", - decoding & HTTP_URI_CODING_HOSTNAME); + uri = http_copy_decode(host, uri, hostlen, "]", decoding & HTTP_URI_CODING_HOSTNAME); if (!uri) { @@ -1135,10 +1001,7 @@ httpSeparateURI( return (HTTP_URI_STATUS_BAD_HOSTNAME); } - /* - * Validate value... - */ - + // Validate value... if (*uri != ']') { *host = '\0'; @@ -1148,21 +1011,16 @@ httpSeparateURI( uri ++; for (ptr = host; *ptr; ptr ++) + { if (*ptr == '+') { - /* - * Convert zone separator to % and stop here... - */ - + // Convert zone separator to % and stop here... *ptr = '%'; break; } else if (*ptr == '%') { - /* - * Stop at zone separator (RFC 6874) - */ - + // Stop at zone separator (RFC 6874) break; } else if (*ptr != ':' && *ptr != '.' && !isxdigit(*ptr & 255)) @@ -1170,34 +1028,30 @@ httpSeparateURI( *host = '\0'; return (HTTP_URI_STATUS_BAD_HOSTNAME); } + } } else { - /* - * Validate the hostname or IPv4 address first... - */ - + // Validate the hostname or IPv4 address first... for (ptr = (char *)uri; *ptr; ptr ++) + { if (strchr(":?/", *ptr)) break; - else if (!strchr("abcdefghijklmnopqrstuvwxyz" /* unreserved */ - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* unreserved */ - "0123456789" /* unreserved */ - "-._~" /* unreserved */ - "%" /* pct-encoded */ - "!$&'()*+,;=" /* sub-delims */ - "\\", *ptr)) /* SMB domain */ + else if (!strchr("abcdefghijklmnopqrstuvwxyz" // unreserved + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // unreserved + "0123456789" // unreserved + "-._~" // unreserved + "%" // pct-encoded + "!$&'()*+,;=" // sub-delims + "\\", *ptr)) // SMB domain { *host = '\0'; return (HTTP_URI_STATUS_BAD_HOSTNAME); } + } - /* - * Then copy the hostname or IPv4 address to the buffer... - */ - - uri = http_copy_decode(host, uri, hostlen, ":?/", - decoding & HTTP_URI_CODING_HOSTNAME); + // Then copy the hostname or IPv4 address to the buffer... + uri = http_copy_decode(host, uri, hostlen, ":?/", decoding & HTTP_URI_CODING_HOSTNAME); if (!uri) { @@ -1206,27 +1060,18 @@ httpSeparateURI( } } - /* - * Validate hostname for file scheme - only empty and localhost are - * acceptable. - */ - + // Validate hostname for file scheme - only empty and localhost are + // acceptable. if (!strcmp(scheme, "file") && strcmp(host, "localhost") && host[0]) { *host = '\0'; return (HTTP_URI_STATUS_BAD_HOSTNAME); } - /* - * See if we have a port number... - */ - + // See if we have a port number... if (*uri == ':') { - /* - * Yes, collect the port number... - */ - + // Yes, collect the port number... if (!isdigit(uri[1] & 255)) { *port = 0; @@ -1249,45 +1094,29 @@ httpSeparateURI( } } - /* - * The remaining portion is the resource string... - */ - + // The remaining portion is the resource string... if (*uri == '?' || !*uri) { - /* - * Hostname but no path... - */ - + // Hostname but no path... status = HTTP_URI_STATUS_MISSING_RESOURCE; *resource = '/'; - /* - * Copy any query string... - */ - + // Copy any query string... if (*uri == '?') - uri = http_copy_decode(resource + 1, uri, resourcelen - 1, NULL, - decoding & HTTP_URI_CODING_QUERY); + uri = http_copy_decode(resource + 1, uri, resourcelen - 1, NULL, decoding & HTTP_URI_CODING_QUERY); else resource[1] = '\0'; } else { - uri = http_copy_decode(resource, uri, resourcelen, "?", - decoding & HTTP_URI_CODING_RESOURCE); + uri = http_copy_decode(resource, uri, resourcelen, "?", decoding & HTTP_URI_CODING_RESOURCE); if (uri && *uri == '?') { - /* - * Concatenate any query string... - */ - + // Concatenate any query string... char *resptr = resource + strlen(resource); - uri = http_copy_decode(resptr, uri, - resourcelen - (int)(resptr - resource), NULL, - decoding & HTTP_URI_CODING_QUERY); + uri = http_copy_decode(resptr, uri, resourcelen - (int)(resptr - resource), NULL, decoding & HTTP_URI_CODING_QUERY); } } @@ -1297,38 +1126,33 @@ httpSeparateURI( return (HTTP_URI_STATUS_BAD_RESOURCE); } - /* - * Return the URI separation status... - */ - + // Return the URI separation status... return (status); } -/* - * '_httpSetDigestAuthString()' - Calculate a Digest authentication response - * using the appropriate RFC 2068/2617/7616 - * algorithm. - */ +// +// '_httpSetDigestAuthString()' - Calculate a Digest authentication response using the appropriate RFC 2068/2617/7616 algorithm. +// -int /* O - 1 on success, 0 on failure */ +int // O - 1 on success, 0 on failure _httpSetDigestAuthString( - http_t *http, /* I - HTTP connection */ - const char *nonce, /* I - Nonce value */ - const char *method, /* I - HTTP method */ - const char *resource) /* I - HTTP resource path */ + http_t *http, // I - HTTP connection + const char *nonce, // I - Nonce value + const char *method, // I - HTTP method + const char *resource) // I - HTTP resource path { - char kd[65], /* Final MD5/SHA-256 digest */ - ha1[65], /* Hash of username:realm:password */ - ha2[65], /* Hash of method:request-uri */ + char kd[65], // Final MD5/SHA-256 digest + ha1[65], // Hash of username:realm:password + ha2[65], // Hash of method:request-uri username[HTTP_MAX_VALUE], - /* username:password */ - *password, /* Pointer to password */ - temp[1024], /* Temporary string */ - digest[1024]; /* Digest auth data */ - unsigned char hash[32]; /* Hash buffer */ - size_t hashsize; /* Size of hash */ - _cups_globals_t *cg = _cupsGlobals(); /* Per-thread globals */ + // username:password + *password, // Pointer to password + temp[1024], // Temporary string + digest[1024]; // Digest auth data + unsigned char hash[32]; // Hash buffer + size_t hashsize; // Size of hash + _cups_globals_t *cg = _cupsGlobals(); // Per-thread globals DEBUG_printf("2_httpSetDigestAuthString(http=%p, nonce=\"%s\", method=\"%s\", resource=\"%s\")", (void *)http, nonce, method, resource); @@ -1343,7 +1167,9 @@ _httpSetDigestAuthString( http->nonce_count = 1; } else + { http->nonce_count ++; + } strlcpy(username, http->userpass, sizeof(username)); if ((password = strchr(username, ':')) != NULL) @@ -1353,13 +1179,10 @@ _httpSetDigestAuthString( if (http->algorithm[0]) { - /* - * Follow RFC 2617/7616... - */ - - int i; /* Looping var */ - char cnonce[65]; /* cnonce value */ - const char *hashalg; /* Hashing algorithm */ + // Follow RFC 2617/7616... + int i; // Looping var + char cnonce[65]; // cnonce value + const char *hashalg; // Hashing algorithm for (i = 0; i < 64; i ++) cnonce[i] = "0123456789ABCDEF"[CUPS_RAND() & 15]; @@ -1367,10 +1190,7 @@ _httpSetDigestAuthString( if (!_cups_strcasecmp(http->algorithm, "MD5")) { - /* - * RFC 2617 Digest with MD5 - */ - + // RFC 2617 Digest with MD5 if (cg->digestoptions == _CUPS_DIGESTOPTIONS_DENYMD5) { DEBUG_puts("3_httpSetDigestAuthString: MD5 Digest is disabled."); @@ -1381,44 +1201,33 @@ _httpSetDigestAuthString( } else if (!_cups_strcasecmp(http->algorithm, "SHA-256")) { - /* - * RFC 7616 Digest with SHA-256 - */ - + // RFC 7616 Digest with SHA-256 hashalg = "sha2-256"; } else { - /* - * Some other algorithm we don't support, skip this one... - */ - + // Some other algorithm we don't support, skip this one... return (0); } - /* - * Calculate digest value... - */ + // Calculate digest value... - /* H(A1) = H(username:realm:password) */ + // H(A1) = H(username:realm:password) snprintf(temp, sizeof(temp), "%s:%s:%s", username, http->realm, password); hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, ha1, sizeof(ha1)); - /* H(A2) = H(method:uri) */ + // H(A2) = H(method:uri) snprintf(temp, sizeof(temp), "%s:%s", method, resource); hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, ha2, sizeof(ha2)); - /* KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */ + // KD = H(H(A1):nonce:nc:cnonce:qop:H(A2)) snprintf(temp, sizeof(temp), "%s:%s:%08x:%s:%s:%s", ha1, http->nonce, http->nonce_count, cnonce, "auth", ha2); hashsize = (size_t)cupsHashData(hashalg, (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, kd, sizeof(kd)); - /* - * Pass the RFC 2617/7616 WWW-Authenticate header... - */ - + // Pass the RFC 2617/7616 WWW-Authenticate header... if (http->opaque[0]) snprintf(digest, sizeof(digest), "username=\"%s\", realm=\"%s\", nonce=\"%s\", algorithm=%s, qop=auth, opaque=\"%s\", cnonce=\"%s\", nc=%08x, uri=\"%s\", response=\"%s\"", cupsGetUser(), http->realm, http->nonce, http->algorithm, http->opaque, cnonce, http->nonce_count, resource, kd); else @@ -1426,35 +1235,29 @@ _httpSetDigestAuthString( } else { - /* - * Use old RFC 2069 Digest method... - */ - + // Use old RFC 2069 Digest method... if (cg->digestoptions == _CUPS_DIGESTOPTIONS_DENYMD5) { DEBUG_puts("3_httpSetDigestAuthString: MD5 Digest is disabled."); return (0); } - /* H(A1) = H(username:realm:password) */ + // H(A1) = H(username:realm:password) snprintf(temp, sizeof(temp), "%s:%s:%s", username, http->realm, password); hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, ha1, sizeof(ha1)); - /* H(A2) = H(method:uri) */ + // H(A2) = H(method:uri) snprintf(temp, sizeof(temp), "%s:%s", method, resource); hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, ha2, sizeof(ha2)); - /* KD = H(H(A1):nonce:H(A2)) */ + // KD = H(H(A1):nonce:H(A2)) snprintf(temp, sizeof(temp), "%s:%s:%s", ha1, http->nonce, ha2); hashsize = (size_t)cupsHashData("md5", (unsigned char *)temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, hashsize, kd, sizeof(kd)); - /* - * Pass the old RFC 2069 WWW-Authenticate header... - */ - + // Pass the old RFC 2069 WWW-Authenticate header... snprintf(digest, sizeof(digest), "username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"", username, http->realm, http->nonce, resource, kd); } @@ -1464,33 +1267,33 @@ _httpSetDigestAuthString( } -/* - * 'httpStateString()' - Return the string describing a HTTP state value. - * - * @since CUPS 2.0/OS 10.10@ - */ +// +// 'httpStateString()' - Return the string describing a HTTP state value. +// +// @since CUPS 2.0/OS 10.10@ +// -const char * /* O - State string */ -httpStateString(http_state_t state) /* I - HTTP state value */ +const char * // O - State string +httpStateString(http_state_t state) // I - HTTP state value { if (state < HTTP_STATE_ERROR || state > HTTP_STATE_UNKNOWN_VERSION) - return ("HTTP_STATE_???"); + return ("???"); else return (http_states[state - HTTP_STATE_ERROR]); } -/* - * '_httpStatusString()' - Return the localized string describing a HTTP status code. - * - * The returned string is localized using the passed message catalog. - */ +// +// '_httpStatusString()' - Return the localized string describing a HTTP status code. +// +// The returned string is localized using the passed message catalog. +// -const char * /* O - Localized status string */ -_httpStatusString(cups_lang_t *lang, /* I - Language */ - http_status_t status) /* I - HTTP status code */ +const char * // O - Localized status string +_httpStatusString(cups_lang_t *lang, // I - Language + http_status_t status) // I - HTTP status code { - const char *s; /* Status string */ + const char *s; // Status string switch (status) @@ -1581,30 +1384,32 @@ _httpStatusString(cups_lang_t *lang, /* I - Language */ } -/* - * 'httpStatus()' - Return a short string describing a HTTP status code. - * - * @deprecated@ @exclude all@ - */ +// +// 'httpStatus()' - Return a short string describing a HTTP status code. +// +// @deprecated@ @exclude all@ +// -const char * /* O - Localized status string */ -httpStatus(http_status_t status) /* I - HTTP status code */ +const char * // O - Localized status string +httpStatus(http_status_t status) // I - HTTP status code { return (httpStatusString(status)); } -/* - * 'httpStatusString()' - Return a short string describing a HTTP status code. - * - * The returned string is localized to the current POSIX locale and is based - * on the status strings defined in RFC 7231. - */ +// +// 'httpStatusString()' - Return a short string describing a HTTP status code. +// +// The returned string is localized to the current POSIX locale and is based +// on the status strings defined in RFC 7231. +// +// @since CUPS 2.5@ +// -const char * /* O - Localized status string */ -httpStatusString(http_status_t status) /* I - HTTP status code */ +const char * // O - Localized status string +httpStatusString(http_status_t status) // I - HTTP status code { - _cups_globals_t *cg = _cupsGlobals(); /* Global data */ + _cups_globals_t *cg = _cupsGlobals(); // Global data if (!cg->lang_default) @@ -1613,18 +1418,18 @@ httpStatusString(http_status_t status) /* I - HTTP status code */ return (_httpStatusString(cg->lang_default, status)); } -/* - * 'httpURIStatusString()' - Return a string describing a URI status code. - * - * @since CUPS 2.0/OS 10.10@ - */ +// +// 'httpURIStatusString()' - Return a string describing a URI status code. +// +// @since CUPS 2.0/OS 10.10@ +// -const char * /* O - Localized status string */ +const char * // O - Localized status string httpURIStatusString( - http_uri_status_t status) /* I - URI status code */ + http_uri_status_t status) // I - URI status code { - const char *s; /* Status string */ - _cups_globals_t *cg = _cupsGlobals(); /* Global data */ + const char *s; // Status string + _cups_globals_t *cg = _cupsGlobals(); // Global data if (!cg->lang_default) @@ -1679,14 +1484,14 @@ httpURIStatusString( #ifndef HAVE_HSTRERROR -/* - * '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others. - */ +// +// '_cups_hstrerror()' - hstrerror() emulation function for Solaris and others. +// -const char * /* O - Error string */ -_cups_hstrerror(int error) /* I - Error number */ +const char * // O - Error string +_cups_hstrerror(int error) // I - Error number { - static const char * const errors[] = /* Error strings */ + static const char * const errors[] = // Error strings { "OK", "Host not found.", @@ -1701,17 +1506,17 @@ _cups_hstrerror(int error) /* I - Error number */ else return (errors[error]); } -#endif /* !HAVE_HSTRERROR */ +#endif // !HAVE_HSTRERROR -/* - * '_httpDecodeURI()' - Percent-decode a HTTP request URI. - */ +// +// '_httpDecodeURI()' - Percent-decode a HTTP request URI. +// -char * /* O - Decoded URI or NULL on error */ -_httpDecodeURI(char *dst, /* I - Destination buffer */ - const char *src, /* I - Source URI */ - size_t dstsize) /* I - Size of destination buffer */ +char * // O - Decoded URI or NULL on error +_httpDecodeURI(char *dst, // I - Destination buffer + const char *src, // I - Source URI + size_t dstsize) // I - Size of destination buffer { if (http_copy_decode(dst, src, (int)dstsize, NULL, 1)) return (dst); @@ -1720,135 +1525,92 @@ _httpDecodeURI(char *dst, /* I - Destination buffer */ } -/* - * '_httpEncodeURI()' - Percent-encode a HTTP request URI. - */ +// +// '_httpEncodeURI()' - Percent-encode a HTTP request URI. +// -char * /* O - Encoded URI */ -_httpEncodeURI(char *dst, /* I - Destination buffer */ - const char *src, /* I - Source URI */ - size_t dstsize) /* I - Size of destination buffer */ +char * // O - Encoded URI +_httpEncodeURI(char *dst, // I - Destination buffer + const char *src, // I - Source URI + size_t dstsize) // I - Size of destination buffer { http_copy_encode(dst, src, dst + dstsize - 1, NULL, NULL, 1); return (dst); } -/* - * '_httpResolveURI()' - Resolve a DNS-SD URI. - */ - -const char * /* O - Resolved URI */ -_httpResolveURI( - const char *uri, /* I - DNS-SD URI */ - char *resolved_uri, /* I - Buffer for resolved URI */ - size_t resolved_size, /* I - Size of URI buffer */ - int options, /* I - Resolve options */ - int (*cb)(void *context), /* I - Continue callback function */ - void *context) /* I - Context pointer for callback */ +// +// 'httpResolveURI()' - Resolve a DNS-SD URI. +// +// This function resolves a DNS-SD URI of the form +// "scheme://service-instance-name._protocol._tcp.domain/...". The "options" +// parameter specifies a bitfield of resolution options including: +// +// - `HTTP_RESOLVE_DEFAULT`: Use default options +// - `HTTP_RESOLVE_FQDN`: Resolve the fully-qualified domain name instead of an IP address +// - `HTTP_RESOLVE_FAXOUT`: Resolve the FaxOut service instead of Print (IPP/IPPS) +// +// The "cb" parameter specifies a callback that allows resolution to be +// terminated. The callback is provided the "cb_data" value and returns a +// `bool` value that is `true` to continue and `false` to stop. If no callback +// is specified ("cb" is `NULL`), then this function will block up to 90 seconds +// to resolve the specified URI. +// + +const char * // O - Resolved URI +httpResolveURI( + const char *uri, // I - DNS-SD URI + char *resolved_uri, // I - Buffer for resolved URI + size_t resolved_size, // I - Size of URI buffer + http_resolve_t options, // I - Resolve options + http_resolve_cb_t cb, // I - Continue callback function + void *cb_data) // I - Context pointer for callback { - char scheme[32], /* URI components... */ + char scheme[32], // URI components... userpass[256], hostname[1024], resource[1024]; int port; #ifdef DEBUG - http_uri_status_t status; /* URI decode status */ -#endif /* DEBUG */ + http_uri_status_t status; // URI decode status +#endif // DEBUG - DEBUG_printf("_httpResolveURI(uri=\"%s\", resolved_uri=%p, resolved_size=" CUPS_LLFMT ", options=0x%x, cb=%p, context=%p)", uri, (void *)resolved_uri, CUPS_LLCAST resolved_size, options, (void *)cb, context); - - /* - * Get the device URI... - */ + DEBUG_printf("httpResolveURI(uri=\"%s\", resolved_uri=%p, resolved_size=" CUPS_LLFMT ", options=0x%x, cb=%p, cb_data=%p)", uri, (void *)resolved_uri, CUPS_LLCAST resolved_size, options, (void *)cb, cb_data); + // Get the device URI... #ifdef DEBUG - if ((status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, - sizeof(scheme), userpass, sizeof(userpass), - hostname, sizeof(hostname), &port, resource, - sizeof(resource))) < HTTP_URI_STATUS_OK) + if ((status = httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, sizeof(resource))) < HTTP_URI_STATUS_OK) #else - if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, - sizeof(scheme), userpass, sizeof(userpass), - hostname, sizeof(hostname), &port, resource, - sizeof(resource)) < HTTP_URI_STATUS_OK) -#endif /* DEBUG */ + if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK) +#endif // DEBUG { - if (options & _HTTP_RESOLVE_STDERR) - _cupsLangPrintFilter(stderr, "ERROR", _("Bad device-uri \"%s\"."), uri); - - DEBUG_printf("2_httpResolveURI: httpSeparateURI returned %d!", status); - DEBUG_puts("2_httpResolveURI: Returning NULL"); + DEBUG_printf("2httpResolveURI: httpSeparateURI returned %d.", status); + DEBUG_puts("1httpResolveURI: Returning NULL"); return (NULL); } - /* - * Resolve it as needed... - */ - + // Resolve it as needed... if (strstr(hostname, "._tcp")) { -#ifdef HAVE_DNSSD - char *regtype, /* Pointer to type in hostname */ - *domain, /* Pointer to domain in hostname */ - *uuid, /* Pointer to UUID in URI */ - *uuidend; /* Pointer to end of UUID in URI */ - _http_uribuf_t uribuf; /* URI buffer */ - int offline = 0; /* offline-report state set? */ -# ifdef HAVE_MDNSRESPONDER - DNSServiceRef ref, /* DNS-SD master service reference */ - domainref = NULL,/* DNS-SD service reference for domain */ - ippref = NULL, /* DNS-SD service reference for network IPP */ - ippsref = NULL, /* DNS-SD service reference for network IPPS */ - localref; /* DNS-SD service reference for .local */ - int extrasent = 0; /* Send the domain/IPP/IPPS resolves? */ -# ifdef HAVE_POLL - struct pollfd polldata; /* Polling data */ -# else /* select() */ - fd_set input_set; /* Input set for select() */ - struct timeval stimeout; /* Timeout value for select() */ -# endif /* HAVE_POLL */ -# elif defined(HAVE_AVAHI) - AvahiClient *client; /* Client information */ - int error; /* Status */ -# endif /* HAVE_MDNSRESPONDER */ - - if (options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Resolving \"%s\"...\n", hostname); - - /* - * Separate the hostname into service name, registration type, and domain... - */ - - for (regtype = strstr(hostname, "._tcp") - 2; - regtype > hostname; - regtype --) - if (regtype[0] == '.' && regtype[1] == '_') - { - /* - * Found ._servicetype in front of ._tcp... - */ - - *regtype++ = '\0'; - break; - } - - if (regtype <= hostname) + time_t domain_time, // Domain lookup time, if any + end_time; // End time for resolve + cups_dnssd_t *dnssd; // DNS-SD context + uint32_t if_index; // Interface index + char name[256], // Service instance name + regtype[256], // Registration type + domain[256], // Domain name + *uuid, // Pointer to UUID in URI + *uuidend; // Pointer to end of UUID in URI + _http_uribuf_t uribuf; // URI buffer + + // Separate the hostname into service name, registration type, and domain... + if (!cupsDNSSDSeparateFullName(hostname, name, sizeof(name), regtype, sizeof(regtype), domain, sizeof(domain))) { - DEBUG_puts("2_httpResolveURI: Bad hostname, returning NULL"); + DEBUG_puts("2httpResolveURI: Bad hostname, returning NULL"); return (NULL); } - for (domain = strchr(regtype, '.'); - domain; - domain = strchr(domain + 1, '.')) - if (domain[1] != '_') - break; - - if (domain) - *domain++ = '\0'; - if ((uuid = strstr(resource, "?uuid=")) != NULL) { *uuid = '\0'; @@ -1865,326 +1627,74 @@ _httpResolveURI( uribuf.resource = resource; uribuf.uuid = uuid; - DEBUG_printf(("2_httpResolveURI: Resolving hostname=\"%s\", regtype=\"%s\", " - "domain=\"%s\"\n", hostname, regtype, domain)); - if (options & _HTTP_RESOLVE_STDERR) - { - fputs("STATE: +connecting-to-device\n", stderr); - fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"%s\", " - "domain=\"local.\"...\n", hostname, regtype); - } + DEBUG_printf("2httpResolveURI: Resolving name=\"%s\", regtype=\"%s\", domain=\"%s\"\n", name, regtype, domain); uri = NULL; -# ifdef HAVE_MDNSRESPONDER - if (DNSServiceCreateConnection(&ref) == kDNSServiceErr_NoError) - { - uint32_t myinterface = kDNSServiceInterfaceIndexAny; - /* Lookup on any interface */ - - if (!strcmp(scheme, "ippusb")) - myinterface = kDNSServiceInterfaceIndexLocalOnly; - - localref = ref; - if (DNSServiceResolve(&localref, - kDNSServiceFlagsShareConnection, myinterface, - hostname, regtype, "local.", http_resolve_cb, - &uribuf) == kDNSServiceErr_NoError) - { - int fds; /* Number of ready descriptors */ - time_t timeout, /* Poll timeout */ - start_time = time(NULL),/* Start time */ - end_time = start_time + 90; - /* End time */ - - while (time(NULL) < end_time) - { - if (options & _HTTP_RESOLVE_STDERR) - _cupsLangPrintFilter(stderr, "INFO", _("Looking for printer.")); - - if (cb && !(*cb)(context)) - { - DEBUG_puts("2_httpResolveURI: callback returned 0 (stop)"); - break; - } - - /* - * Wakeup every 2 seconds to emit a "looking for printer" message... - */ - - if ((timeout = end_time - time(NULL)) > 2) - timeout = 2; - -# ifdef HAVE_POLL - polldata.fd = DNSServiceRefSockFD(ref); - polldata.events = POLLIN; - - fds = poll(&polldata, 1, (int)(1000 * timeout)); - -# else /* select() */ - FD_ZERO(&input_set); - FD_SET(DNSServiceRefSockFD(ref), &input_set); - -# ifdef _WIN32 - stimeout.tv_sec = (long)timeout; -# else - stimeout.tv_sec = timeout; -# endif /* _WIN32 */ - stimeout.tv_usec = 0; - - fds = select(DNSServiceRefSockFD(ref)+1, &input_set, NULL, NULL, - &stimeout); -# endif /* HAVE_POLL */ + if (!strcmp(scheme, "ippusb")) + if_index = CUPS_DNSSD_IF_INDEX_LOCAL; + else + if_index = CUPS_DNSSD_IF_INDEX_ANY; - if (fds < 0) - { - if (errno != EINTR && errno != EAGAIN) - { - DEBUG_printf("2_httpResolveURI: poll error: %s", strerror(errno)); - break; - } - } - else if (fds == 0) - { - /* - * Wait 2 seconds for a response to the local resolve; if nothing - * comes in, do an additional domain resolution... - */ - - if (extrasent == 0 && domain && _cups_strcasecmp(domain, "local.")) - { - if (options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, - "DEBUG: Resolving \"%s\", regtype=\"%s\", " - "domain=\"%s\"...\n", hostname, regtype, - domain ? domain : ""); - - domainref = ref; - if (DNSServiceResolve(&domainref, - kDNSServiceFlagsShareConnection, - myinterface, hostname, regtype, domain, - http_resolve_cb, - &uribuf) == kDNSServiceErr_NoError) - extrasent = 1; - } - else if (extrasent == 0 && !strcmp(scheme, "ippusb")) - { - if (options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"_ipps._tcp\", domain=\"local.\"...\n", hostname); - - ippsref = ref; - if (DNSServiceResolve(&ippsref, - kDNSServiceFlagsShareConnection, - kDNSServiceInterfaceIndexAny, hostname, - "_ipps._tcp", domain, http_resolve_cb, - &uribuf) == kDNSServiceErr_NoError) - extrasent = 1; - } - else if (extrasent == 1 && !strcmp(scheme, "ippusb")) - { - if (options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Resolving \"%s\", regtype=\"_ipp._tcp\", domain=\"local.\"...\n", hostname); - - ippref = ref; - if (DNSServiceResolve(&ippref, - kDNSServiceFlagsShareConnection, - kDNSServiceInterfaceIndexAny, hostname, - "_ipp._tcp", domain, http_resolve_cb, - &uribuf) == kDNSServiceErr_NoError) - extrasent = 2; - } - - /* - * If it hasn't resolved within 5 seconds set the offline-report - * printer-state-reason... - */ - - if ((options & _HTTP_RESOLVE_STDERR) && offline == 0 && - time(NULL) > (start_time + 5)) - { - fputs("STATE: +offline-report\n", stderr); - offline = 1; - } - } - else - { - if (DNSServiceProcessResult(ref) == kDNSServiceErr_NoError && - resolved_uri[0]) - { - uri = resolved_uri; - break; - } - } - } + dnssd = cupsDNSSDNew(NULL, NULL); - if (extrasent) - { - if (domainref) - DNSServiceRefDeallocate(domainref); - if (ippref) - DNSServiceRefDeallocate(ippref); - if (ippsref) - DNSServiceRefDeallocate(ippsref); - } + if (!cupsDNSSDResolveNew(dnssd, if_index, name, regtype, "local.", http_resolve_cb, &uribuf)) + { + cupsDNSSDDelete(dnssd); + return (NULL); + } - DNSServiceRefDeallocate(localref); - } + domain_time = time(NULL) + 2; + end_time = time(NULL) + 90; - DNSServiceRefDeallocate(ref); - } -# else /* HAVE_AVAHI */ - if ((uribuf.poll = avahi_simple_poll_new()) != NULL) + while (!resolved_uri[0] && time(NULL) < end_time) { - avahi_simple_poll_set_func(uribuf.poll, http_poll_cb, NULL); - - if ((client = avahi_client_new(avahi_simple_poll_get(uribuf.poll), - 0, http_client_cb, - &uribuf, &error)) != NULL) + // Start the domain resolve as needed... + if (time(NULL) >= domain_time && _cups_strcasecmp(domain, "local.")) { - if (avahi_service_resolver_new(client, AVAHI_IF_UNSPEC, - AVAHI_PROTO_UNSPEC, hostname, - regtype, "local.", AVAHI_PROTO_UNSPEC, 0, - http_resolve_cb, &uribuf) != NULL) - { - time_t start_time = time(NULL), - /* Start time */ - end_time = start_time + 90; - /* End time */ - int pstatus; /* Poll status */ - - pstatus = avahi_simple_poll_iterate(uribuf.poll, 2000); - - if (pstatus == 0 && !resolved_uri[0] && domain && - _cups_strcasecmp(domain, "local.")) - { - /* - * Resolve for .local hasn't returned anything, try the listed - * domain... - */ - - avahi_service_resolver_new(client, AVAHI_IF_UNSPEC, - AVAHI_PROTO_UNSPEC, hostname, - regtype, domain, AVAHI_PROTO_UNSPEC, 0, - http_resolve_cb, &uribuf); - } - - while (!pstatus && !resolved_uri[0] && time(NULL) < end_time) - { - if ((pstatus = avahi_simple_poll_iterate(uribuf.poll, 2000)) != 0) - break; - - /* - * If it hasn't resolved within 5 seconds set the offline-report - * printer-state-reason... - */ - - if ((options & _HTTP_RESOLVE_STDERR) && offline == 0 && - time(NULL) > (start_time + 5)) - { - fputs("STATE: +offline-report\n", stderr); - offline = 1; - } - } - - /* - * Collect the result (if we got one). - */ - - if (resolved_uri[0]) - uri = resolved_uri; - } - - avahi_client_free(client); + cupsDNSSDResolveNew(dnssd, if_index, name, regtype, domain, http_resolve_cb, &uribuf); + domain_time = end_time; } - avahi_simple_poll_free(uribuf.poll); - } -# endif /* HAVE_MDNSRESPONDER */ + // Sleep 1/4 second to allow time for resolve... + usleep(250000); - if (options & _HTTP_RESOLVE_STDERR) - { - if (uri) - { - fprintf(stderr, "DEBUG: Resolved as \"%s\"...\n", uri); - fputs("STATE: -connecting-to-device,offline-report\n", stderr); - } - else - { - fputs("DEBUG: Unable to resolve URI\n", stderr); - fputs("STATE: -connecting-to-device\n", stderr); - } + if (resolved_uri[0]) + break; } -#else /* !HAVE_DNSSD */ - /* - * No DNS-SD support... - */ + cupsDNSSDDelete(dnssd); - uri = NULL; -#endif /* HAVE_DNSSD */ - - if ((options & _HTTP_RESOLVE_STDERR) && !uri) - _cupsLangPrintFilter(stderr, "INFO", _("Unable to find printer.")); + // Save the results of the resolve... + uri = *resolved_uri ? resolved_uri : NULL; } else { - /* - * Nothing more to do... - */ - - strlcpy(resolved_uri, uri, resolved_size); + // Nothing more to do... + cupsCopyString(resolved_uri, uri, resolved_size); uri = resolved_uri; } - DEBUG_printf("2_httpResolveURI: Returning \"%s\"", uri); + DEBUG_printf("2httpResolveURI: Returning \"%s\"", uri); return (uri); } -#ifdef HAVE_AVAHI -/* - * 'http_client_cb()' - Client callback for resolving URI. - */ - -static void -http_client_cb( - AvahiClient *client, /* I - Client information */ - AvahiClientState state, /* I - Current state */ - void *context) /* I - Pointer to URI buffer */ -{ - DEBUG_printf(("7http_client_cb(client=%p, state=%d, context=%p)", client, - state, context)); - - /* - * If the connection drops, quit. - */ - - if (state == AVAHI_CLIENT_FAILURE) - { - _http_uribuf_t *uribuf = (_http_uribuf_t *)context; - /* URI buffer */ - - avahi_simple_poll_quit(uribuf->poll); - } -} -#endif /* HAVE_AVAHI */ - - -/* - * 'http_copy_decode()' - Copy and decode a URI. - */ +// +// 'http_copy_decode()' - Copy and decode a URI. +// -static const char * /* O - New source pointer or NULL on error */ -http_copy_decode(char *dst, /* O - Destination buffer */ - const char *src, /* I - Source pointer */ - int dstsize, /* I - Destination size */ - const char *term, /* I - Terminating characters */ - int decode) /* I - Decode %-encoded values */ +static const char * // O - New source pointer or NULL on error +http_copy_decode(char *dst, // O - Destination buffer + const char *src, // I - Source pointer + size_t dstsize, // I - Destination size + const char *term, // I - Terminating characters + int decode) // I - Decode %-encoded values { - char *ptr, /* Pointer into buffer */ - *end; /* End of buffer */ - int quoted; /* Quoted character */ + char *ptr, // Pointer into buffer + *end; // End of buffer + int quoted; // Quoted character /* @@ -2244,17 +1754,17 @@ http_copy_decode(char *dst, /* O - Destination buffer */ } -/* - * 'http_copy_encode()' - Copy and encode a URI. - */ +// +// 'http_copy_encode()' - Copy and encode a URI. +// -static char * /* O - End of current URI */ -http_copy_encode(char *dst, /* O - Destination buffer */ - const char *src, /* I - Source pointer */ - char *dstend, /* I - End of destination buffer */ - const char *reserved, /* I - Extra reserved characters */ - const char *term, /* I - Terminating characters */ - int encode) /* I - %-encode reserved chars? */ +static char * // O - End of current URI +http_copy_encode(char *dst, // O - Destination buffer + const char *src, // I - Source pointer + char *dstend, // I - End of destination buffer + const char *reserved, // I - Extra reserved characters + const char *term, // I - Terminating characters + int encode) // I - %-encode reserved chars? { static const char hex[] = "0123456789ABCDEF"; @@ -2293,443 +1803,130 @@ http_copy_encode(char *dst, /* O - Destination buffer */ } -#ifdef HAVE_MDNSRESPONDER -/* - * 'http_resolve_cb()' - Build a device URI for the given service name. - */ +// +// 'http_resolve_cb()' - Build a device URI for the given service name. +// -static void DNSSD_API +static void http_resolve_cb( - DNSServiceRef sdRef, /* I - Service reference */ - DNSServiceFlags flags, /* I - Results flags */ - uint32_t interfaceIndex, /* I - Interface number */ - DNSServiceErrorType errorCode, /* I - Error, if any */ - const char *fullName, /* I - Full service name */ - const char *hostTarget, /* I - Hostname */ - uint16_t port, /* I - Port number */ - uint16_t txtLen, /* I - Length of TXT record */ - const unsigned char *txtRecord, /* I - TXT record data */ - void *context) /* I - Pointer to URI buffer */ + cups_dnssd_resolve_t *res, // I - Resolver + void *cb_data, // I - Pointer to URI buffer + cups_dnssd_flags_t flags, // I - Results flags + uint32_t if_index, // I - Interface index + const char *fullname, // I - Full service name + const char *host, // I - Hostname + uint16_t port, // I - Port number + size_t num_txt, // I - Number of TXT key/value pairs + cups_option_t *txt) // I - TXT key/value pairs { - _http_uribuf_t *uribuf = (_http_uribuf_t *)context; - /* URI buffer */ - const char *scheme, /* URI scheme */ - *hostptr, /* Pointer into hostTarget */ - *reskey, /* "rp" or "rfo" */ - *resdefault; /* Default path */ - char resource[257], /* Remote path */ - fqdn[256]; /* FQDN of the .local name */ - const void *value; /* Value from TXT record */ - uint8_t valueLen; /* Length of value */ + _http_uribuf_t *uribuf = (_http_uribuf_t *)cb_data; + // URI buffer + const char *scheme, // URI scheme + *hostptr, // Pointer into hostTarget + *reskey, // "rp" or "rfo" + *resdefault; // Default path + char fqdn[256]; // FQDN of the .local name + const char *value, // Value from TXT record + *resource; // Resource path - DEBUG_printf("4http_resolve_cb(sdRef=%p, flags=%x, interfaceIndex=%u, errorCode=%d, fullName=\"%s\", hostTarget=\"%s\", port=%u, txtLen=%u, txtRecord=%p, context=%p)", (void *)sdRef, flags, interfaceIndex, errorCode, fullName, hostTarget, port, txtLen, (void *)txtRecord, context); + DEBUG_printf("4http_resolve_cb(res=%p, cb_data=%p, flags=%x, if_index=%u, fullname=\"%s\", host=\"%s\", port=%u, num_txt=%u, txt=%p)", (void *)res, cb_data, flags, if_index, fullname, host, port, (unsigned)num_txt, (void *)txt); - /* - * If we have a UUID, compare it... - */ - - if (uribuf->uuid && - (value = TXTRecordGetValuePtr(txtLen, txtRecord, "UUID", - &valueLen)) != NULL) + // If we have a UUID, compare it... + if (uribuf->uuid && (value = cupsGetOption("UUID", num_txt, txt)) != NULL) { - char uuid[256]; /* UUID value */ - - memcpy(uuid, value, valueLen); - uuid[valueLen] = '\0'; - - if (_cups_strcasecmp(uuid, uribuf->uuid)) + if (_cups_strcasecmp(value, uribuf->uuid)) { - if (uribuf->options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Found UUID %s, looking for %s.", uuid, - uribuf->uuid); - - DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid, - uribuf->uuid)); + DEBUG_printf("5http_resolve_cb: Found UUID %s, looking for %s.", value, uribuf->uuid); return; } } - /* - * Figure out the scheme from the full name... - */ - - if (strstr(fullName, "._ipps") || strstr(fullName, "._ipp-tls")) + // Figure out the scheme from the full name... + if (strstr(fullname, "._ipps") || strstr(fullname, "._ipp-tls")) scheme = "ipps"; - else if (strstr(fullName, "._ipp") || strstr(fullName, "._fax-ipp")) + else if (strstr(fullname, "._ipp") || strstr(fullname, "._fax-ipp")) scheme = "ipp"; - else if (strstr(fullName, "._http.")) + else if (strstr(fullname, "._http.")) scheme = "http"; - else if (strstr(fullName, "._https.")) + else if (strstr(fullname, "._https.")) scheme = "https"; - else if (strstr(fullName, "._printer.")) + else if (strstr(fullname, "._printer.")) scheme = "lpd"; - else if (strstr(fullName, "._pdl-datastream.")) + else if (strstr(fullname, "._pdl-datastream.")) scheme = "socket"; else scheme = "riousbprint"; - /* - * Extract the "remote printer" key from the TXT record... - */ - - if ((uribuf->options & _HTTP_RESOLVE_FAXOUT) && - (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) && - !TXTRecordGetValuePtr(txtLen, txtRecord, "printer-type", &valueLen)) + // Extract the "remote printer" key from the TXT record... + if ((uribuf->options & HTTP_RESOLVE_FAXOUT) && (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) && !cupsGetOption("printer-type", num_txt, txt)) { reskey = "rfo"; - resdefault = "/ipp/faxout"; + resdefault = "ipp/faxout"; } else { reskey = "rp"; - resdefault = "/"; + resdefault = ""; } - if ((value = TXTRecordGetValuePtr(txtLen, txtRecord, reskey, - &valueLen)) != NULL) + if ((resource = cupsGetOption(reskey, num_txt, txt)) != NULL) { - if (((char *)value)[0] == '/') + // Use the resource path from the TXT record... + if (*resource == '/') { - /* - * Value (incorrectly) has a leading slash already... - */ - - memcpy(resource, value, valueLen); - resource[valueLen] = '\0'; - } - else - { - /* - * Convert to resource by concatenating with a leading "/"... - */ - - resource[0] = '/'; - memcpy(resource + 1, value, valueLen); - resource[valueLen + 1] = '\0'; + // Value (incorrectly) has a leading slash already... + resource ++; } } else { - /* - * Use the default value... - */ - - strlcpy(resource, resdefault, sizeof(resource)); + // Use the default resource path... + resource = resdefault; } - /* - * Lookup the FQDN if needed... - */ - - if ((uribuf->options & _HTTP_RESOLVE_FQDN) && - (hostptr = hostTarget + strlen(hostTarget) - 7) > hostTarget && - !_cups_strcasecmp(hostptr, ".local.")) + // Lookup the FQDN if needed... + if ((uribuf->options & HTTP_RESOLVE_FQDN) && (hostptr = host + strlen(host) - 7) > host && !_cups_strcasecmp(hostptr, ".local.")) { - /* - * OK, we got a .local name but the caller needs a real domain. Start by - * getting the IP address of the .local name and then do reverse-lookups... - */ + // OK, we got a .local name but the caller needs a real domain. Start by + // getting the IP address of the .local name and then do reverse-lookups... + http_addrlist_t *addrlist, // List of addresses + *addr; // Current address - http_addrlist_t *addrlist, /* List of addresses */ - *addr; /* Current address */ - - DEBUG_printf("5http_resolve_cb: Looking up \"%s\".", hostTarget); + DEBUG_printf("5http_resolve_cb: Looking up \"%s\".", host); snprintf(fqdn, sizeof(fqdn), "%d", ntohs(port)); - if ((addrlist = httpAddrGetList(hostTarget, AF_UNSPEC, fqdn)) != NULL) + if ((addrlist = httpAddrGetList(host, AF_UNSPEC, fqdn)) != NULL) { for (addr = addrlist; addr; addr = addr->next) { - int error = getnameinfo(&(addr->addr.addr), (socklen_t)httpAddrLength(&(addr->addr)), fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD); + int error = getnameinfo(&(addr->addr.addr), (socklen_t)httpAddrGetLength(&(addr->addr)), fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD); if (!error) { DEBUG_printf("5http_resolve_cb: Found \"%s\".", fqdn); - if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn || - _cups_strcasecmp(hostptr, ".local")) + if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn || _cups_strcasecmp(hostptr, ".local")) { - hostTarget = fqdn; + host = fqdn; break; } } #ifdef DEBUG else - DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d", - httpAddrString(&(addr->addr), fqdn, sizeof(fqdn)), - error)); -#endif /* DEBUG */ + DEBUG_printf("5http_resolve_cb: \"%s\" did not resolve: %d", httpAddrGetString(&(addr->addr), fqdn, sizeof(fqdn)), error); +#endif // DEBUG } httpAddrFreeList(addrlist); } } - /* - * Assemble the final device URI... - */ - - if ((!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) && - !strcmp(uribuf->resource, "/cups")) - httpAssembleURIf(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme, NULL, hostTarget, ntohs(port), "%s?snmp=false", resource); + // Assemble the final URI... + if ((!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) && !strcmp(uribuf->resource, "/cups")) + httpAssembleURIf(HTTP_URI_CODING_ALL, uribuf->buffer, uribuf->bufsize, scheme, NULL, host, port, "/%s?snmp=false", resource); else - httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme, NULL, hostTarget, ntohs(port), resource); + httpAssembleURIf(HTTP_URI_CODING_ALL, uribuf->buffer, uribuf->bufsize, scheme, NULL, host, port, "/%s", resource); DEBUG_printf("5http_resolve_cb: Resolved URI is \"%s\"...", uribuf->buffer); } - -#elif defined(HAVE_AVAHI) -/* - * 'http_poll_cb()' - Wait for input on the specified file descriptors. - * - * Note: This function is needed because avahi_simple_poll_iterate is broken - * and always uses a timeout of 0 (!) milliseconds. - * (Avahi Ticket #364) - * - * @private@ - */ - -static int /* O - Number of file descriptors matching */ -http_poll_cb( - struct pollfd *pollfds, /* I - File descriptors */ - unsigned int num_pollfds, /* I - Number of file descriptors */ - int timeout, /* I - Timeout in milliseconds (used) */ - void *context) /* I - User data (unused) */ -{ - (void)timeout; - (void)context; - - return (poll(pollfds, num_pollfds, 2000)); -} - - -/* - * 'http_resolve_cb()' - Build a device URI for the given service name. - */ - -static void -http_resolve_cb( - AvahiServiceResolver *resolver, /* I - Resolver (unused) */ - AvahiIfIndex interface, /* I - Interface index */ - AvahiProtocol protocol, /* I - Network protocol (unused) */ - AvahiResolverEvent event, /* I - Event (found, etc.) */ - const char *name, /* I - Service name */ - const char *type, /* I - Registration type */ - const char *domain, /* I - Domain (unused) */ - const char *hostTarget, /* I - Hostname */ - const AvahiAddress *address, /* I - Address (unused) */ - uint16_t port, /* I - Port number */ - AvahiStringList *txt, /* I - TXT record */ - AvahiLookupResultFlags flags, /* I - Lookup flags (unused) */ - void *context) /* I - Pointer to URI buffer */ -{ - _http_uribuf_t *uribuf = (_http_uribuf_t *)context; - /* URI buffer */ - const char *scheme, /* URI scheme */ - *hostptr, /* Pointer into hostTarget */ - *reskey, /* "rp" or "rfo" */ - *resdefault; /* Default path */ - char resource[257], /* Remote path */ - fqdn[256]; /* FQDN of the .local name */ - char ifname[IF_NAMESIZE]; - /* Interface name */ - AvahiStringList *pair; /* Current TXT record key/value pair */ - char *value; /* Value for "rp" key */ - size_t valueLen = 0; /* Length of "rp" key */ - - - DEBUG_printf(("4http_resolve_cb(resolver=%p, " - "interface=%d, protocol=%d, event=%d, name=\"%s\", " - "type=\"%s\", domain=\"%s\", hostTarget=\"%s\", address=%p, " - "port=%d, txt=%p, flags=%d, context=%p)", - resolver, interface, protocol, event, name, type, domain, - hostTarget, address, port, txt, flags, context)); - - if (event != AVAHI_RESOLVER_FOUND) - { - avahi_service_resolver_free(resolver); - avahi_simple_poll_quit(uribuf->poll); - return; - } - - /* - * If we have a UUID, compare it... - */ - - if (uribuf->uuid && (pair = avahi_string_list_find(txt, "UUID")) != NULL) - { - char uuid[256]; /* UUID value */ - - avahi_string_list_get_pair(pair, NULL, &value, &valueLen); - - memcpy(uuid, value, valueLen); - uuid[valueLen] = '\0'; - - avahi_free(value); - - if (_cups_strcasecmp(uuid, uribuf->uuid)) - { - if (uribuf->options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Found UUID %s, looking for %s.", uuid, - uribuf->uuid); - - DEBUG_printf(("5http_resolve_cb: Found UUID %s, looking for %s.", uuid, - uribuf->uuid)); - return; - } - } - - /* - * Figure out the scheme from the full name... - */ - - if (!strncmp(type, "_ipps.", 6) || !strncmp(type, "_ipp-tls.", 9)) - scheme = "ipps"; - else if (!strncmp(type, "_ipp.", 5) || !strncmp(type, "_fax-ipp.", 9)) - scheme = "ipp"; - else if (!strncmp(type, "_http.", 6)) - scheme = "http"; - else if (!strncmp(type, "_https.", 7)) - scheme = "https"; - else if (!strncmp(type, "_printer.", 9)) - scheme = "lpd"; - else if (!strncmp(type, "_pdl-datastream.", 16)) - scheme = "socket"; - else - { - avahi_service_resolver_free(resolver); - avahi_simple_poll_quit(uribuf->poll); - return; - } - - /* - * Extract the remote resource key from the TXT record... - */ - - if ((uribuf->options & _HTTP_RESOLVE_FAXOUT) && - (!strcmp(scheme, "ipp") || !strcmp(scheme, "ipps")) && - !avahi_string_list_find(txt, "printer-type")) - { - reskey = "rfo"; - resdefault = "/ipp/faxout"; - } - else - { - reskey = "rp"; - resdefault = "/"; - } - - if ((pair = avahi_string_list_find(txt, reskey)) != NULL) - { - avahi_string_list_get_pair(pair, NULL, &value, &valueLen); - - if (value[0] == '/') - { - /* - * Value (incorrectly) has a leading slash already... - */ - - memcpy(resource, value, valueLen); - resource[valueLen] = '\0'; - } - else - { - /* - * Convert to resource by concatenating with a leading "/"... - */ - - resource[0] = '/'; - memcpy(resource + 1, value, valueLen); - resource[valueLen + 1] = '\0'; - } - - avahi_free(value); - } - else - { - /* - * Use the default value... - */ - - strlcpy(resource, resdefault, sizeof(resource)); - } - - /* - * Get the name of the interface this is coming from... - */ - - if (!if_indextoname((unsigned int)interface, ifname)) - { - if (uribuf->options & _HTTP_RESOLVE_STDERR) - fprintf(stderr, "DEBUG: Unable to find interface name for interface %d: %s\n", interface, strerror(errno)); - DEBUG_printf("Unable to find interface name for interface %d: %s\n", interface, strerror(errno)); - ifname[0] = '\0'; - } - - if (!strcmp(ifname, "lo")) - { - /* - * If this service is registered on loopback interface ("lo"), force the host - * name to "localhost"... - */ - - if (uribuf->options & _HTTP_RESOLVE_STDERR) - fputs("DEBUG: Service comes from loopback interface \"lo\", setting \"localhost\" as host name.\n", stderr); - DEBUG_puts("Service comes from loopback interface \"lo\", setting \"localhost\" as host name."); - hostTarget = "localhost"; - } - else if ((uribuf->options & _HTTP_RESOLVE_FQDN) && - (hostptr = hostTarget + strlen(hostTarget) - 6) > hostTarget && - !_cups_strcasecmp(hostptr, ".local")) - { - /* - * OK, we got a .local name but the caller needs a real domain. Start by - * getting the IP address of the .local name and then do reverse-lookups... - */ - - http_addrlist_t *addrlist, /* List of addresses */ - *addr; /* Current address */ - - DEBUG_printf("5http_resolve_cb: Looking up \"%s\".", hostTarget); - - snprintf(fqdn, sizeof(fqdn), "%d", ntohs(port)); - if ((addrlist = httpAddrGetList(hostTarget, AF_UNSPEC, fqdn)) != NULL) - { - for (addr = addrlist; addr; addr = addr->next) - { - int error = getnameinfo(&(addr->addr.addr), (socklen_t)httpAddrLength(&(addr->addr)), fqdn, sizeof(fqdn), NULL, 0, NI_NAMEREQD); - - if (!error) - { - DEBUG_printf("5http_resolve_cb: Found \"%s\".", fqdn); - - if ((hostptr = fqdn + strlen(fqdn) - 6) <= fqdn || - _cups_strcasecmp(hostptr, ".local")) - { - hostTarget = fqdn; - break; - } - } -#ifdef DEBUG - else - DEBUG_printf(("5http_resolve_cb: \"%s\" did not resolve: %d", - httpAddrString(&(addr->addr), fqdn, sizeof(fqdn)), - error)); -#endif /* DEBUG */ - } - - httpAddrFreeList(addrlist); - } - } - - /* - * Assemble the final device URI using the resolved hostname... - */ - - httpAssembleURI(HTTP_URI_CODING_ALL, uribuf->buffer, (int)uribuf->bufsize, scheme, NULL, hostTarget, port, resource); - DEBUG_printf("5http_resolve_cb: Resolved URI is \"%s\".", uribuf->buffer); - - avahi_simple_poll_quit(uribuf->poll); -} -#endif /* HAVE_MDNSRESPONDER */ diff --git a/cups/http.c b/cups/http.c index 4c174fd500..39780bed5d 100644 --- a/cups/http.c +++ b/cups/http.c @@ -446,8 +446,7 @@ httpConnectEncrypt( int port, // I - Port number http_encryption_t encryption) // I - Type of encryption to use { - DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)", - host, port, encryption)); + DEBUG_printf("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)", host, port, encryption); return (httpConnect2(host, port, NULL, AF_UNSPEC, encryption, 1, 30000, NULL)); } @@ -2181,8 +2180,7 @@ httpReconnect2(http_t *http, // I - HTTP connection #endif // _WIN32 http->status = HTTP_STATUS_ERROR; - DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s", - strerror(http->error))); + DEBUG_printf("1httpReconnect2: httpAddrConnect failed: %s", strerror(http->error)); return (-1); } @@ -3899,13 +3897,11 @@ http_read_chunk(http_t *http, // I - HTTP connection if (http->data_remaining < 0) { - DEBUG_printf(("8http_read_chunk: Negative chunk length \"%s\" (" - CUPS_LLFMT ")", len, CUPS_LLCAST http->data_remaining)); + DEBUG_printf("8http_read_chunk: Negative chunk length \"%s\" (" CUPS_LLFMT ")", len, CUPS_LLCAST http->data_remaining); return (0); } - DEBUG_printf(("8http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT ")", - len, CUPS_LLCAST http->data_remaining)); + DEBUG_printf("8http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT ")", len, CUPS_LLCAST http->data_remaining); if (http->data_remaining == 0) { diff --git a/cups/http.h b/cups/http.h index f5a34b7391..3b8aab83f4 100644 --- a/cups/http.h +++ b/cups/http.h @@ -423,12 +423,14 @@ extern time_t httpCredentialsGetExpiration(cups_array_t *credentials) _CUPS_DEP extern http_trust_t httpCredentialsGetTrust(cups_array_t *credentials, const char *common_name) _CUPS_DEPRECATED_MSG("Use cupsGetCredentialsTrust instead."); extern size_t httpCredentialsString(cups_array_t *credentials, char *buffer, size_t bufsize) _CUPS_DEPRECATED_MSG("Use cupsGetCredentialsInfo instead."); -extern char *httpDecode64(char *out, const char *in) _CUPS_DEPRECATED_MSG("Use httpDecode64_2 instead."); -extern char *httpDecode64_2(char *out, int *outlen, const char *in) _CUPS_PUBLIC; +extern char *httpDecode64(char *out, const char *in) _CUPS_DEPRECATED_MSG("Use httpDecode64_3 instead."); +extern char *httpDecode64_2(char *out, int *outlen, const char *in) _CUPS_DEPRECATED_MSG("Use httpDecode64_3 instead."); +extern char *httpDecode64_3(char *out, size_t *outlen, const char *in, const char **end) _CUPS_PUBLIC; extern int httpDelete(http_t *http, const char *uri) _CUPS_DEPRECATED_MSG("Use httpWriteRequest instead."); extern char *httpEncode64(char *out, const char *in) _CUPS_DEPRECATED_MSG("Use httpEncode64_2 instead."); extern char *httpEncode64_2(char *out, int outlen, const char *in, int inlen) _CUPS_PUBLIC; +extern char *httpEncode64_3(char *out, size_t outlen, const char *in, size_t inlen, bool url) _CUPS_PUBLIC; extern int httpEncryption(http_t *http, http_encryption_t e) _CUPS_DEPRECATED_MSG("Use httpSetEncryption instead."); extern int httpError(http_t *http) _CUPS_DEPRECATED_MSG("Use httpGetError instead."); diff --git a/cups/ipp-vars.c b/cups/ipp-vars.c index 9c7da667f3..6eb124761f 100644 --- a/cups/ipp-vars.c +++ b/cups/ipp-vars.c @@ -229,7 +229,7 @@ _ippVarsSet(_ipp_vars_t *v, /* I - IPP variables */ * Resolve URI... */ - if (!_httpResolveURI(value, resolved, sizeof(resolved), _HTTP_RESOLVE_DEFAULT, NULL, NULL)) + if (!httpResolveURI(value, resolved, sizeof(resolved), HTTP_RESOLVE_DEFAULT, NULL, NULL)) return (0); value = resolved; diff --git a/cups/ipp.c b/cups/ipp.c index 8f4da22ca2..0c75216970 100644 --- a/cups/ipp.c +++ b/cups/ipp.c @@ -731,8 +731,7 @@ ippAddResolution(ipp_t *ipp, /* I - IPP message */ ipp_attribute_t *attr; /* New attribute */ - DEBUG_printf(("ippAddResolution(ipp=%p, group=%02x(%s), name=\"%s\", units=%d, xres=%d, yres=%d)", (void *)ipp, group, - ippTagString(group), name, units, xres, yres)); + DEBUG_printf("ippAddResolution(ipp=%p, group=%02x(%s), name=\"%s\", units=%d, xres=%d, yres=%d)", (void *)ipp, group, ippTagString(group), name, units, xres, yres); /* * Range check input... @@ -1402,9 +1401,7 @@ ippContainsString( * Compare... */ - DEBUG_printf(("1ippContainsString: attr %s, %s with %d values.", - attr->name, ippTagString(attr->value_tag), - attr->num_values)); + DEBUG_printf("1ippContainsString: attr %s, %s with %d values.", attr->name, ippTagString(attr->value_tag), attr->num_values); switch (attr->value_tag & IPP_TAG_CUPS_MASK) { @@ -1417,8 +1414,7 @@ ippContainsString( i > 0; i --, avalue ++) { - DEBUG_printf(("1ippContainsString: value[%d]=\"%s\"", - attr->num_values - i, avalue->string.text)); + DEBUG_printf("1ippContainsString: value[%d]=\"%s\"", attr->num_values - i, avalue->string.text); if (!strcmp(value, avalue->string.text)) { @@ -1436,8 +1432,7 @@ ippContainsString( i > 0; i --, avalue ++) { - DEBUG_printf(("1ippContainsString: value[%d]=\"%s\"", - attr->num_values - i, avalue->string.text)); + DEBUG_printf("1ippContainsString: value[%d]=\"%s\"", attr->num_values - i, avalue->string.text); if (!_cups_strcasecmp(value, avalue->string.text)) { @@ -2914,10 +2909,8 @@ ippReadIO(void *src, /* I - Data source */ ipp->request.any.request_id = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | buffer[7]; DEBUG_printf("2ippReadIO: version=%d.%d", buffer[0], buffer[1]); - DEBUG_printf(("2ippReadIO: op_status=%04x", - ipp->request.any.op_status)); - DEBUG_printf(("2ippReadIO: request_id=%d", - ipp->request.any.request_id)); + DEBUG_printf("2ippReadIO: op_status=%04x", ipp->request.any.op_status); + DEBUG_printf("2ippReadIO: request_id=%d", ipp->request.any.request_id); } ipp->state = IPP_STATE_ATTRIBUTE; @@ -3015,8 +3008,7 @@ ippReadIO(void *src, /* I - Data source */ continue; } - DEBUG_printf(("2ippReadIO: value tag=%x(%s)", tag, - ippTagString(tag))); + DEBUG_printf("2ippReadIO: value tag=%x(%s)", tag, ippTagString(tag)); /* * Get the name... @@ -3091,16 +3083,13 @@ ippReadIO(void *src, /* I - Data source */ _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP 1setOf attribute with incompatible value " "tags."), 1); - DEBUG_printf(("1ippReadIO: 1setOf value tag %x(%s) != %x(%s)", - value_tag, ippTagString(value_tag), tag, - ippTagString(tag))); + DEBUG_printf("1ippReadIO: 1setOf value tag %x(%s) != %x(%s)", value_tag, ippTagString(value_tag), tag, ippTagString(tag)); goto rollback; } if (value_tag != tag) { - DEBUG_printf(("1ippReadIO: Converting %s attribute from %s to %s.", - attr->name, ippTagString(value_tag), ippTagString(tag))); + DEBUG_printf("1ippReadIO: Converting %s attribute from %s to %s.", attr->name, ippTagString(value_tag), ippTagString(tag)); ippSetValueTag(ipp, &attr, tag); } } @@ -3117,9 +3106,7 @@ ippReadIO(void *src, /* I - Data source */ _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP 1setOf attribute with incompatible value " "tags."), 1); - DEBUG_printf(("1ippReadIO: 1setOf value tag %x(%s) != %x(%s)", - value_tag, ippTagString(value_tag), tag, - ippTagString(tag))); + DEBUG_printf("1ippReadIO: 1setOf value tag %x(%s) != %x(%s)", value_tag, ippTagString(value_tag), tag, ippTagString(tag)); goto rollback; } @@ -3129,8 +3116,7 @@ ippReadIO(void *src, /* I - Data source */ * Convert integer values to rangeOfInteger values... */ - DEBUG_printf(("1ippReadIO: Converting %s attribute to " - "rangeOfInteger.", attr->name)); + DEBUG_printf("1ippReadIO: Converting %s attribute to rangeOfInteger.", attr->name); ippSetValueTag(ipp, &attr, IPP_TAG_RANGE); } } @@ -3139,9 +3125,7 @@ ippReadIO(void *src, /* I - Data source */ _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP 1setOf attribute with incompatible value " "tags."), 1); - DEBUG_printf(("1ippReadIO: value tag %x(%s) != %x(%s)", - value_tag, ippTagString(value_tag), tag, - ippTagString(tag))); + DEBUG_printf("1ippReadIO: value tag %x(%s) != %x(%s)", value_tag, ippTagString(value_tag), tag, ippTagString(tag)); goto rollback; } @@ -3368,10 +3352,8 @@ ippReadIO(void *src, /* I - Data source */ case IPP_TAG_RANGE : if (n != 8) { - _cupsSetError(IPP_STATUS_ERROR_INTERNAL, - _("IPP rangeOfInteger value not 8 bytes."), 1); - DEBUG_printf(("1ippReadIO: bad rangeOfInteger value length " - "%d.", n)); + _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP rangeOfInteger value not 8 bytes."), 1); + DEBUG_printf("1ippReadIO: bad rangeOfInteger value length %d.", n); goto rollback; } @@ -3397,8 +3379,7 @@ ippReadIO(void *src, /* I - Data source */ _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP nameWithLanguage value less than " "minimum 4 bytes."), 1); - DEBUG_printf(("1ippReadIO: bad stringWithLanguage value " - "length %d.", n)); + DEBUG_printf("1ippReadIO: bad stringWithLanguage value length %d.", n); goto rollback; } @@ -3428,16 +3409,14 @@ ippReadIO(void *src, /* I - Data source */ { _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP language length overflows value."), 1); - DEBUG_printf(("1ippReadIO: bad language value length %d.", - n)); + DEBUG_printf("1ippReadIO: bad language value length %d.", n); goto rollback; } else if (n >= IPP_MAX_LANGUAGE) { _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP language length too large."), 1); - DEBUG_printf(("1ippReadIO: bad language value length %d.", - n)); + DEBUG_printf("1ippReadIO: bad language value length %d.", n); goto rollback; } @@ -3545,8 +3524,7 @@ ippReadIO(void *src, /* I - Data source */ { _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("IPP octetString length too large."), 1); - DEBUG_printf(("1ippReadIO: bad octetString value length %d.", - n)); + DEBUG_printf("1ippReadIO: bad octetString value length %d.", n); goto rollback; } @@ -5301,10 +5279,8 @@ ippWriteIO(void *dst, /* I - Destination */ *bufptr++ = (ipp_uchar_t)ipp->request.any.request_id; DEBUG_printf("2ippWriteIO: version=%d.%d", buffer[0], buffer[1]); - DEBUG_printf(("2ippWriteIO: op_status=%04x", - ipp->request.any.op_status)); - DEBUG_printf(("2ippWriteIO: request_id=%d", - ipp->request.any.request_id)); + DEBUG_printf("2ippWriteIO: op_status=%04x", ipp->request.any.op_status); + DEBUG_printf("2ippWriteIO: request_id=%d", ipp->request.any.request_id); if ((*cb)(dst, buffer, (size_t)(bufptr - buffer)) < 0) { @@ -5357,17 +5333,14 @@ ippWriteIO(void *dst, /* I - Destination */ if (attr->group_tag == IPP_TAG_ZERO) continue; - DEBUG_printf(("2ippWriteIO: wrote group tag=%x(%s)", - attr->group_tag, ippTagString(attr->group_tag))); + DEBUG_printf("2ippWriteIO: wrote group tag=%x(%s)", attr->group_tag, ippTagString(attr->group_tag)); *bufptr++ = (ipp_uchar_t)attr->group_tag; } else if (attr->group_tag == IPP_TAG_ZERO) continue; } - DEBUG_printf(("1ippWriteIO: %s (%s%s)", attr->name, - attr->num_values > 1 ? "1setOf " : "", - ippTagString(attr->value_tag))); + DEBUG_printf("1ippWriteIO: %s (%s%s)", attr->name, attr->num_values > 1 ? "1setOf " : "", ippTagString(attr->value_tag)); /* * Write the attribute tag and name. @@ -5396,10 +5369,8 @@ ippWriteIO(void *dst, /* I - Destination */ * Write the value tag, name length, and name string... */ - DEBUG_printf(("2ippWriteIO: writing value tag=%x(%s)", - attr->value_tag, ippTagString(attr->value_tag))); - DEBUG_printf(("2ippWriteIO: writing name=%d,\"%s\"", n, - attr->name)); + DEBUG_printf("2ippWriteIO: writing value tag=%x(%s)", attr->value_tag, ippTagString(attr->value_tag)); + DEBUG_printf("2ippWriteIO: writing name=%d,\"%s\"", n, attr->name); if (attr->value_tag > 0xff) { @@ -5436,12 +5407,9 @@ ippWriteIO(void *dst, /* I - Destination */ * and empty name for the collection member attribute... */ - DEBUG_printf(("2ippWriteIO: writing value tag=%x(memberName)", - IPP_TAG_MEMBERNAME)); - DEBUG_printf(("2ippWriteIO: writing name=%d,\"%s\"", n, - attr->name)); - DEBUG_printf(("2ippWriteIO: writing value tag=%x(%s)", - attr->value_tag, ippTagString(attr->value_tag))); + DEBUG_printf("2ippWriteIO: writing value tag=%x(memberName)", IPP_TAG_MEMBERNAME); + DEBUG_printf("2ippWriteIO: writing name=%d,\"%s\"", n, attr->name); + DEBUG_printf("2ippWriteIO: writing value tag=%x(%s)", attr->value_tag, ippTagString(attr->value_tag)); DEBUG_puts("2ippWriteIO: writing name=0,\"\""); *bufptr++ = IPP_TAG_MEMBERNAME; @@ -5592,9 +5560,7 @@ ippWriteIO(void *dst, /* I - Destination */ * values with a zero-length name... */ - DEBUG_printf(("2ippWriteIO: writing value tag=%x(%s)", - attr->value_tag, - ippTagString(attr->value_tag))); + DEBUG_printf("2ippWriteIO: writing value tag=%x(%s)", attr->value_tag, ippTagString(attr->value_tag)); DEBUG_printf("2ippWriteIO: writing name=0,\"\""); if ((IPP_BUF_SIZE - (bufptr - buffer)) < 3) @@ -5627,8 +5593,7 @@ ippWriteIO(void *dst, /* I - Destination */ return (IPP_STATE_ERROR); } - DEBUG_printf(("2ippWriteIO: writing string=%d,\"%s\"", n, - value->string.text)); + DEBUG_printf("2ippWriteIO: writing string=%d,\"%s\"", n, value->string.text); if ((int)(IPP_BUF_SIZE - (bufptr - buffer)) < (n + 2)) { @@ -5864,8 +5829,7 @@ ippWriteIO(void *dst, /* I - Destination */ if (n > (IPP_BUF_SIZE - 2)) { - DEBUG_printf(("1ippWriteIO: text/nameWithLanguage value " - "too long (%d)", n)); + DEBUG_printf("1ippWriteIO: text/nameWithLanguage value too long (%d)", n); _cupsBufferRelease((char *)buffer); return (IPP_STATE_ERROR); } @@ -6032,8 +5996,7 @@ ippWriteIO(void *dst, /* I - Destination */ if (n > (IPP_BUF_SIZE - 2)) { - DEBUG_printf(("1ippWriteIO: Data length too long (%d)", - n)); + DEBUG_printf("1ippWriteIO: Data length too long (%d)", n); _cupsBufferRelease((char *)buffer); return (IPP_STATE_ERROR); } @@ -6078,8 +6041,7 @@ ippWriteIO(void *dst, /* I - Destination */ return (IPP_STATE_ERROR); } - DEBUG_printf(("2ippWriteIO: wrote %d bytes", - (int)(bufptr - buffer))); + DEBUG_printf("2ippWriteIO: wrote %d bytes", (int)(bufptr - buffer)); } /* @@ -6424,8 +6386,7 @@ ipp_length(ipp_t *ipp, /* I - IPP message or collection */ if (!attr->name) continue; - DEBUG_printf(("5ipp_length: attr->name=\"%s\", attr->num_values=%d, " - "bytes=" CUPS_LLFMT, attr->name, attr->num_values, CUPS_LLCAST bytes)); + DEBUG_printf("5ipp_length: attr->name=\"%s\", attr->num_values=%d, bytes=" CUPS_LLFMT, attr->name, attr->num_values, CUPS_LLCAST bytes); if ((attr->value_tag & ~IPP_TAG_CUPS_CONST) < IPP_TAG_EXTENSION) bytes += (size_t)attr->num_values;/* Value tag for each value */ @@ -6712,8 +6673,7 @@ ipp_set_value(ipp_t *ipp, /* IO - IPP message */ else alloc_values += IPP_MAX_VALUES; - DEBUG_printf(("4ipp_set_value: Reallocating for up to %d values.", - alloc_values)); + DEBUG_printf("4ipp_set_value: Reallocating for up to %d values.", alloc_values); /* * Reallocate memory... diff --git a/cups/options.c b/cups/options.c index 82da41872a..cbc51ce77b 100644 --- a/cups/options.c +++ b/cups/options.c @@ -104,8 +104,7 @@ cupsAddOption(const char *name, /* I - Name of option */ * No matching option name... */ - DEBUG_printf(("4cupsAddOption: New option inserted at index %d...", - insert)); + DEBUG_printf("4cupsAddOption: New option inserted at index %d...", insert); if (num_options == 0) temp = (cups_option_t *)malloc(sizeof(cups_option_t)); @@ -122,8 +121,7 @@ cupsAddOption(const char *name, /* I - Name of option */ if (insert < num_options) { - DEBUG_printf(("4cupsAddOption: Shifting %d options...", - (int)(num_options - insert))); + DEBUG_printf("4cupsAddOption: Shifting %d options...", (int)(num_options - insert)); memmove(temp + insert + 1, temp + insert, (size_t)(num_options - insert) * sizeof(cups_option_t)); } @@ -137,8 +135,7 @@ cupsAddOption(const char *name, /* I - Name of option */ * Match found; free the old value... */ - DEBUG_printf(("4cupsAddOption: Option already exists at index %d...", - insert)); + DEBUG_printf("4cupsAddOption: Option already exists at index %d...", insert); temp = *options + insert; _cupsStrFree(temp->value); @@ -653,8 +650,7 @@ cups_find_option( #ifdef DEBUG for (left = 0; left < num_options; left ++) - DEBUG_printf(("9cups_find_option: options[%d].name=\"%s\", .value=\"%s\"", - left, options[left].name, options[left].value)); + DEBUG_printf("9cups_find_option: options[%d].name=\"%s\", .value=\"%s\"", left, options[left].name, options[left].value); #endif /* DEBUG */ key.name = (char *)name; diff --git a/cups/ppd-attr.c b/cups/ppd-attr.c index c25af26294..23756d703a 100644 --- a/cups/ppd-attr.c +++ b/cups/ppd-attr.c @@ -32,8 +32,7 @@ ppdFindAttr(ppd_file_t *ppd, /* I - PPD file data */ *attr; /* Current attribute */ - DEBUG_printf(("2ppdFindAttr(ppd=%p, name=\"%s\", spec=\"%s\")", ppd, name, - spec)); + DEBUG_printf("2ppdFindAttr(ppd=%p, name=\"%s\", spec=\"%s\")", ppd, name, spec); /* * Range check input... diff --git a/cups/ppd-cache.c b/cups/ppd-cache.c index f65514001a..c83f47da27 100644 --- a/cups/ppd-cache.c +++ b/cups/ppd-cache.c @@ -554,8 +554,7 @@ _ppdCacheCreateWithFile( if (atoi(line + 16) != _PPD_CACHE_VERSION) { _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Out of date PPD cache file."), 1); - DEBUG_printf(("_ppdCacheCreateWithFile: Cache file has version %s, " - "expected %d.", line + 16, _PPD_CACHE_VERSION)); + DEBUG_printf("_ppdCacheCreateWithFile: Cache file has version %s, expected %d.", line + 16, _PPD_CACHE_VERSION); cupsFileClose(fp); return (NULL); } @@ -585,13 +584,11 @@ _ppdCacheCreateWithFile( while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum)) { - DEBUG_printf(("_ppdCacheCreateWithFile: line=\"%s\", value=\"%s\", " - "linenum=%d", line, value, linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: line=\"%s\", value=\"%s\", linenum=%d", line, value, linenum); if (!value) { - DEBUG_printf(("_ppdCacheCreateWithFile: Missing value on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Missing value on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -679,16 +676,14 @@ _ppdCacheCreateWithFile( if ((num_bins = atoi(value)) <= 0 || num_bins > 65536) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad NumBins value %d on line " - "%d.", num_sizes, linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad NumBins value %d on line %d.", num_sizes, linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if ((pc->bins = calloc((size_t)num_bins, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithFile: Unable to allocate %d bins.", - num_sizes)); + DEBUG_printf("_ppdCacheCreateWithFile: Unable to allocate %d bins.", num_sizes); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); goto create_error; } @@ -704,8 +699,7 @@ _ppdCacheCreateWithFile( if (pc->num_bins >= num_bins) { - DEBUG_printf(("_ppdCacheCreateWithFile: Too many Bin's on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Too many Bin's on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -727,8 +721,7 @@ _ppdCacheCreateWithFile( if ((num_sizes = atoi(value)) < 0 || num_sizes > 65536) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad NumSizes value %d on line " - "%d.", num_sizes, linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad NumSizes value %d on line %d.", num_sizes, linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -737,8 +730,7 @@ _ppdCacheCreateWithFile( { if ((pc->sizes = calloc((size_t)num_sizes, sizeof(pwg_size_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithFile: Unable to allocate %d sizes.", - num_sizes)); + DEBUG_printf("_ppdCacheCreateWithFile: Unable to allocate %d sizes.", num_sizes); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); goto create_error; } @@ -748,8 +740,7 @@ _ppdCacheCreateWithFile( { if (pc->num_sizes >= num_sizes) { - DEBUG_printf(("_ppdCacheCreateWithFile: Too many Size's on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Too many Size's on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -760,8 +751,7 @@ _ppdCacheCreateWithFile( &(size->width), &(size->length), &(size->left), &(size->bottom), &(size->right), &(size->top)) != 8) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad Size on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad Size on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -775,8 +765,7 @@ _ppdCacheCreateWithFile( { if (pc->custom_max_width > 0) { - DEBUG_printf(("_ppdCacheCreateWithFile: Too many CustomSize's on line " - "%d.", linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Too many CustomSize's on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -787,8 +776,7 @@ _ppdCacheCreateWithFile( &(pc->custom_size.bottom), &(pc->custom_size.right), &(pc->custom_size.top)) != 8) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad CustomSize on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad CustomSize on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -817,16 +805,14 @@ _ppdCacheCreateWithFile( if ((num_sources = atoi(value)) <= 0 || num_sources > 65536) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad NumSources value %d on " - "line %d.", num_sources, linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad NumSources value %d on line %d.", num_sources, linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if ((pc->sources = calloc((size_t)num_sources, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithFile: Unable to allocate %d sources.", - num_sources)); + DEBUG_printf("_ppdCacheCreateWithFile: Unable to allocate %d sources.", num_sources); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); goto create_error; } @@ -835,16 +821,14 @@ _ppdCacheCreateWithFile( { if (sscanf(value, "%127s%40s", pwg_keyword, ppd_keyword) != 2) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad Source on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad Source on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if (pc->num_sources >= num_sources) { - DEBUG_printf(("_ppdCacheCreateWithFile: Too many Source's on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Too many Source's on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -866,16 +850,14 @@ _ppdCacheCreateWithFile( if ((num_types = atoi(value)) <= 0 || num_types > 65536) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad NumTypes value %d on " - "line %d.", num_types, linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad NumTypes value %d on line %d.", num_types, linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if ((pc->types = calloc((size_t)num_types, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithFile: Unable to allocate %d types.", - num_types)); + DEBUG_printf("_ppdCacheCreateWithFile: Unable to allocate %d types.", num_types); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0); goto create_error; } @@ -884,16 +866,14 @@ _ppdCacheCreateWithFile( { if (sscanf(value, "%127s%40s", pwg_keyword, ppd_keyword) != 2) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad Type on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad Type on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if (pc->num_types >= num_types) { - DEBUG_printf(("_ppdCacheCreateWithFile: Too many Type's on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Too many Type's on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -919,8 +899,7 @@ _ppdCacheCreateWithFile( print_quality >= _PWG_PRINT_QUALITY_MAX || valueptr == value || !*valueptr) { - DEBUG_printf(("_ppdCacheCreateWithFile: Bad Preset on line %d.", - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Bad Preset on line %d.", linenum); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -987,31 +966,27 @@ _ppdCacheCreateWithFile( } else { - DEBUG_printf(("_ppdCacheCreateWithFile: Unknown %s on line %d.", line, - linenum)); + DEBUG_printf("_ppdCacheCreateWithFile: Unknown %s on line %d.", line, linenum); } } if (pc->num_sizes < num_sizes) { - DEBUG_printf(("_ppdCacheCreateWithFile: Not enough sizes (%d < %d).", - pc->num_sizes, num_sizes)); + DEBUG_printf("_ppdCacheCreateWithFile: Not enough sizes (%d < %d).", pc->num_sizes, num_sizes); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if (pc->num_sources < num_sources) { - DEBUG_printf(("_ppdCacheCreateWithFile: Not enough sources (%d < %d).", - pc->num_sources, num_sources)); + DEBUG_printf("_ppdCacheCreateWithFile: Not enough sources (%d < %d).", pc->num_sources, num_sources); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } if (pc->num_types < num_types) { - DEBUG_printf(("_ppdCacheCreateWithFile: Not enough types (%d < %d).", - pc->num_types, num_types)); + DEBUG_printf("_ppdCacheCreateWithFile: Not enough types (%d < %d).", pc->num_types, num_types); _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad PPD cache file."), 1); goto create_error; } @@ -1120,8 +1095,7 @@ _ppdCacheCreateWithPPD(ppd_file_t *ppd) /* I - PPD file */ { if ((pc->sizes = calloc((size_t)ppd->num_sizes, sizeof(pwg_size_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithPPD: Unable to allocate %d " - "pwg_size_t's.", ppd->num_sizes)); + DEBUG_printf("_ppdCacheCreateWithPPD: Unable to allocate %d pwg_size_t's.", ppd->num_sizes); goto create_error; } @@ -1298,8 +1272,7 @@ _ppdCacheCreateWithPPD(ppd_file_t *ppd) /* I - PPD file */ if ((pc->sources = calloc((size_t)input_slot->num_choices, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithPPD: Unable to allocate %d " - "pwg_map_t's for InputSlot.", input_slot->num_choices)); + DEBUG_printf("_ppdCacheCreateWithPPD: Unable to allocate %d pwg_map_t's for InputSlot.", input_slot->num_choices); goto create_error; } @@ -1393,8 +1366,7 @@ _ppdCacheCreateWithPPD(ppd_file_t *ppd) /* I - PPD file */ if ((pc->types = calloc((size_t)media_type->num_choices, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithPPD: Unable to allocate %d " - "pwg_map_t's for MediaType.", media_type->num_choices)); + DEBUG_printf("_ppdCacheCreateWithPPD: Unable to allocate %d pwg_map_t's for MediaType.", media_type->num_choices); goto create_error; } @@ -1483,8 +1455,7 @@ _ppdCacheCreateWithPPD(ppd_file_t *ppd) /* I - PPD file */ { if ((pc->bins = calloc((size_t)output_bin->num_choices, sizeof(pwg_map_t))) == NULL) { - DEBUG_printf(("_ppdCacheCreateWithPPD: Unable to allocate %d " - "pwg_map_t's for OutputBin.", output_bin->num_choices)); + DEBUG_printf("_ppdCacheCreateWithPPD: Unable to allocate %d pwg_map_t's for OutputBin.", output_bin->num_choices); goto create_error; } @@ -2526,8 +2497,7 @@ _ppdCacheGetPageSize( const char *ppd_name; /* PPD media name */ - DEBUG_printf(("_ppdCacheGetPageSize(pc=%p, job=%p, keyword=\"%s\", exact=%p)", - pc, job, keyword, exact)); + DEBUG_printf("_ppdCacheGetPageSize(pc=%p, job=%p, keyword=\"%s\", exact=%p)", pc, job, keyword, exact); /* * Range check input... @@ -2555,8 +2525,7 @@ _ppdCacheGetPageSize( #ifdef DEBUG if (attr) - DEBUG_printf(("1_ppdCacheGetPageSize: Found attribute %s (%s)", - attr->name, ippTagString(attr->value_tag))); + DEBUG_printf("1_ppdCacheGetPageSize: Found attribute %s (%s)", attr->name, ippTagString(attr->value_tag)); else DEBUG_puts("1_ppdCacheGetPageSize: Did not find media attribute."); #endif /* DEBUG */ @@ -2576,8 +2545,7 @@ _ppdCacheGetPageSize( for (i = pc->num_sizes, size = pc->sizes; i > 0; i --, size ++) { - DEBUG_printf(("2_ppdCacheGetPageSize: size[%d]=[\"%s\" \"%s\"]", - (int)(size - pc->sizes), size->map.pwg, size->map.ppd)); + DEBUG_printf("2_ppdCacheGetPageSize: size[%d]=[\"%s\" \"%s\"]", (int)(size - pc->sizes), size->map.pwg, size->map.ppd); if (!_cups_strcasecmp(ppd_name, size->map.ppd) || !_cups_strcasecmp(ppd_name, size->map.pwg)) @@ -2686,8 +2654,7 @@ _ppdCacheGetPageSize( if (closest) { - DEBUG_printf(("1_ppdCacheGetPageSize: Returning \"%s\" (closest)", - closest->map.ppd)); + DEBUG_printf("1_ppdCacheGetPageSize: Returning \"%s\" (closest)", closest->map.ppd); return (closest->map.ppd); } @@ -2722,8 +2689,7 @@ _ppdCacheGetPageSize( else if (exact) *exact = 1; - DEBUG_printf(("1_ppdCacheGetPageSize: Returning \"%s\" (custom)", - pc->custom_ppd_size)); + DEBUG_printf("1_ppdCacheGetPageSize: Returning \"%s\" (custom)", pc->custom_ppd_size); return (pc->custom_ppd_size); } diff --git a/cups/ppd-conflicts.c b/cups/ppd-conflicts.c index 26111002b6..0d73540bec 100644 --- a/cups/ppd-conflicts.c +++ b/cups/ppd-conflicts.c @@ -249,23 +249,20 @@ cupsResolveConflicts( * Resolver loop! */ - DEBUG_printf(("1cupsResolveConflicts: Resolver loop with %s!", - consts->resolver)); + DEBUG_printf("1cupsResolveConflicts: Resolver loop with %s!", consts->resolver); goto error; } if ((resolver = ppdFindAttr(ppd, "cupsUIResolver", consts->resolver)) == NULL) { - DEBUG_printf(("1cupsResolveConflicts: Resolver %s not found!", - consts->resolver)); + DEBUG_printf("1cupsResolveConflicts: Resolver %s not found!", consts->resolver); goto error; } if (!resolver->value) { - DEBUG_printf(("1cupsResolveConflicts: Resolver %s has no value!", - consts->resolver)); + DEBUG_printf("1cupsResolveConflicts: Resolver %s has no value!", consts->resolver); goto error; } @@ -531,8 +528,7 @@ cupsResolveConflicts( DEBUG_printf("1cupsResolveConflicts: Returning %d options:", num_newopts); #ifdef DEBUG for (i = 0; i < num_newopts; i ++) - DEBUG_printf(("1cupsResolveConflicts: options[%d]: %s=%s", i, - newopts[i].name, newopts[i].value)); + DEBUG_printf("1cupsResolveConflicts: options[%d]: %s=%s", i, newopts[i].name, newopts[i].value); #endif /* DEBUG */ return (1); @@ -641,8 +637,7 @@ ppdInstallableConflict( cups_array_t *active; /* Active conflicts */ - DEBUG_printf(("2ppdInstallableConflict(ppd=%p, option=\"%s\", choice=\"%s\")", - ppd, option, choice)); + DEBUG_printf("2ppdInstallableConflict(ppd=%p, option=\"%s\", choice=\"%s\")", ppd, option, choice); /* * Range check input... @@ -793,8 +788,7 @@ ppd_load_constraints(ppd_file_t *ppd) /* I - PPD file */ if (!constptr[0].option || (!constptr[0].choice && oldconst->choice1[0])) { - DEBUG_printf(("8ppd_load_constraints: Unknown option *%s %s!", - oldconst->option1, oldconst->choice1)); + DEBUG_printf("8ppd_load_constraints: Unknown option *%s %s!", oldconst->option1, oldconst->choice1); free(consts->constraints); free(consts); continue; @@ -818,8 +812,7 @@ ppd_load_constraints(ppd_file_t *ppd) /* I - PPD file */ if (!constptr[1].option || (!constptr[1].choice && oldconst->choice2[0])) { - DEBUG_printf(("8ppd_load_constraints: Unknown option *%s %s!", - oldconst->option2, oldconst->choice2)); + DEBUG_printf("8ppd_load_constraints: Unknown option *%s %s!", oldconst->option2, oldconst->choice2); free(consts->constraints); free(consts); continue; @@ -919,8 +912,7 @@ ppd_load_constraints(ppd_file_t *ppd) /* I - PPD file */ if (!constptr->option || (!constptr->choice && choice[0])) { - DEBUG_printf(("8ppd_load_constraints: Unknown option *%s %s!", - option, choice)); + DEBUG_printf("8ppd_load_constraints: Unknown option *%s %s!", option, choice); break; } } @@ -960,15 +952,12 @@ ppd_test_constraints( char firstpage[255]; /* AP_FIRSTPAGE_Keyword string */ - DEBUG_printf(("7ppd_test_constraints(ppd=%p, option=\"%s\", choice=\"%s\", " - "num_options=%d, options=%p, which=%d)", ppd, option, choice, - num_options, options, which)); + DEBUG_printf("7ppd_test_constraints(ppd=%p, option=\"%s\", choice=\"%s\", num_options=%d, options=%p, which=%d)", ppd, option, choice, num_options, options, which); if (!ppd->cups_uiconstraints) ppd_load_constraints(ppd); - DEBUG_printf(("9ppd_test_constraints: %d constraints!", - cupsArrayCount(ppd->cups_uiconstraints))); + DEBUG_printf("9ppd_test_constraints: %d constraints!", cupsArrayCount(ppd->cups_uiconstraints)); cupsArraySave(ppd->marked); @@ -976,16 +965,7 @@ ppd_test_constraints( consts; consts = (_ppd_cups_uiconsts_t *)cupsArrayNext(ppd->cups_uiconstraints)) { - DEBUG_printf(("9ppd_test_constraints: installable=%d, resolver=\"%s\", " - "num_constraints=%d option1=\"%s\", choice1=\"%s\", " - "option2=\"%s\", choice2=\"%s\", ...", - consts->installable, consts->resolver, consts->num_constraints, - consts->constraints[0].option->keyword, - consts->constraints[0].choice ? - consts->constraints[0].choice->choice : "", - consts->constraints[1].option->keyword, - consts->constraints[1].choice ? - consts->constraints[1].choice->choice : "")); + DEBUG_printf("9ppd_test_constraints: installable=%d, resolver=\"%s\", num_constraints=%d option1=\"%s\", choice1=\"%s\", option2=\"%s\", choice2=\"%s\", ...", consts->installable, consts->resolver, consts->num_constraints, consts->constraints[0].option->keyword, consts->constraints[0].choice ? consts->constraints[0].choice->choice : "", consts->constraints[1].option->keyword, consts->constraints[1].choice ? consts->constraints[1].choice->choice : ""); if (consts->installable && which < _PPD_INSTALLABLE_CONSTRAINTS) continue; /* Skip installable option constraint */ @@ -1021,8 +1001,7 @@ ppd_test_constraints( i > 0; i --, constptr ++) { - DEBUG_printf(("9ppd_test_constraints: %s=%s?", constptr->option->keyword, - constptr->choice ? constptr->choice->choice : "")); + DEBUG_printf("9ppd_test_constraints: %s=%s?", constptr->option->keyword, constptr->choice ? constptr->choice->choice : ""); if (constptr->choice && (!_cups_strcasecmp(constptr->option->keyword, "PageSize") || @@ -1123,8 +1102,7 @@ ppd_test_constraints( else firstvalue = NULL; - DEBUG_printf(("9ppd_test_constraints: value=%s, firstvalue=%s", value, - firstvalue)); + DEBUG_printf("9ppd_test_constraints: value=%s, firstvalue=%s", value, firstvalue); if ((!value || _cups_strcasecmp(value, constptr->choice->choice)) && (!firstvalue || _cups_strcasecmp(firstvalue, constptr->choice->choice))) @@ -1181,8 +1159,7 @@ ppd_test_constraints( cupsArrayRestore(ppd->marked); - DEBUG_printf(("8ppd_test_constraints: Found %d active constraints!", - cupsArrayCount(active))); + DEBUG_printf("8ppd_test_constraints: Found %d active constraints!", cupsArrayCount(active)); return (active); } diff --git a/cups/ppd-mark.c b/cups/ppd-mark.c index 1be1a4becb..be43e51dae 100644 --- a/cups/ppd-mark.c +++ b/cups/ppd-mark.c @@ -406,8 +406,7 @@ ppdFindMarkedChoice(ppd_file_t *ppd, /* I - PPD file */ marked = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key); - DEBUG_printf(("3ppdFindMarkedChoice: Returning %p(%s)...", marked, - marked ? marked->choice : "NULL")); + DEBUG_printf("3ppdFindMarkedChoice: Returning %p(%s)...", marked, marked ? marked->choice : "NULL"); return (marked); } @@ -542,8 +541,7 @@ ppdMarkOption(ppd_file_t *ppd, /* I - PPD file record */ const char *option, /* I - Keyword */ const char *choice) /* I - Option name */ { - DEBUG_printf(("ppdMarkOption(ppd=%p, option=\"%s\", choice=\"%s\")", - ppd, option, choice)); + DEBUG_printf("ppdMarkOption(ppd=%p, option=\"%s\", choice=\"%s\")", ppd, option, choice); /* * Range check input... @@ -776,8 +774,7 @@ ppd_mark_option(ppd_file_t *ppd, /* I - PPD file */ struct lconv *loc; /* Locale data */ - DEBUG_printf(("7ppd_mark_option(ppd=%p, option=\"%s\", choice=\"%s\")", - ppd, option, choice)); + DEBUG_printf("7ppd_mark_option(ppd=%p, option=\"%s\", choice=\"%s\")", ppd, option, choice); /* * AP_D_InputSlot is the "default input slot" on macOS, and setting diff --git a/cups/ppd-util.c b/cups/ppd-util.c index 86118b6edb..aed4cbe741 100644 --- a/cups/ppd-util.c +++ b/cups/ppd-util.c @@ -631,7 +631,7 @@ cups_get_printer_uri( } else if ((attr = ippFindAttribute(response, "printer-uri-supported", IPP_TAG_URI)) != NULL) { - httpSeparateURI(HTTP_URI_CODING_ALL, _httpResolveURI(attr->values[0].string.text, uri, sizeof(uri), _HTTP_RESOLVE_DEFAULT, NULL, NULL), scheme, sizeof(scheme), username, sizeof(username), host, hostsize, port, resource, resourcesize); + httpSeparateURI(HTTP_URI_CODING_ALL, httpResolveURI(attr->values[0].string.text, uri, sizeof(uri), HTTP_RESOLVE_DEFAULT, NULL, NULL), scheme, sizeof(scheme), username, sizeof(username), host, hostsize, port, resource, resourcesize); ippDelete(response); DEBUG_printf("5cups_get_printer_uri: Resolved to host=\"%s\", port=%d, resource=\"%s\"", host, *port, resource); diff --git a/cups/ppd.c b/cups/ppd.c index 5473ba1596..f40bdc0a2e 100644 --- a/cups/ppd.c +++ b/cups/ppd.c @@ -579,8 +579,7 @@ _ppdOpen( ll_CC_len = strlen(ll_CC); ll_len = strlen(ll); - DEBUG_printf(("2_ppdOpen: Loading localizations matching \"%s\" and \"%s\"", - ll_CC, ll)); + DEBUG_printf("2_ppdOpen: Loading localizations matching \"%s\" and \"%s\"", ll_CC, ll); } /* @@ -650,9 +649,7 @@ _ppdOpen( while ((mask = ppd_read(fp, &line, keyword, name, text, &string, 1, pg)) != 0) { - DEBUG_printf(("2_ppdOpen: mask=%x, keyword=\"%s\", name=\"%s\", " - "text=\"%s\", string=%d chars...", mask, keyword, name, text, - string ? (int)strlen(string) : 0)); + DEBUG_printf("2_ppdOpen: mask=%x, keyword=\"%s\", name=\"%s\", text=\"%s\", string=%d chars...", mask, keyword, name, text, string ? (int)strlen(string) : 0); if (strncmp(keyword, "Default", 7) && !string && pg->ppd_conform != PPD_CONFORM_RELAXED) @@ -751,8 +748,7 @@ _ppdOpen( ui_keyword = 1; - DEBUG_printf(("2_ppdOpen: FOUND ADOBE UI KEYWORD %s WITHOUT OPENUI!", - keyword)); + DEBUG_printf("2_ppdOpen: FOUND ADOBE UI KEYWORD %s WITHOUT OPENUI!", keyword); if (!group) { @@ -795,8 +791,7 @@ _ppdOpen( !strcmp(ppd->attrs[j]->name + 7, keyword) && ppd->attrs[j]->value) { - DEBUG_printf(("2_ppdOpen: Setting Default%s to %s via attribute...", - option->keyword, ppd->attrs[j]->value)); + DEBUG_printf("2_ppdOpen: Setting Default%s to %s via attribute...", option->keyword, ppd->attrs[j]->value); strlcpy(option->defchoice, ppd->attrs[j]->value, sizeof(option->defchoice)); break; @@ -1278,8 +1273,7 @@ _ppdOpen( for (i = (int)strlen(name) - 1; i > 0 && _cups_isspace(name[i]); i --) name[i] = '\0'; /* Eliminate trailing spaces */ - DEBUG_printf(("2_ppdOpen: OpenUI of %s in group %s...", name, - group ? group->text : "(null)")); + DEBUG_printf("2_ppdOpen: OpenUI of %s in group %s...", name, group ? group->text : "(null)"); if (subgroup != NULL) option = ppd_get_option(subgroup, name); @@ -1327,8 +1321,7 @@ _ppdOpen( !strcmp(ppd->attrs[j]->name + 7, name) && ppd->attrs[j]->value) { - DEBUG_printf(("2_ppdOpen: Setting Default%s to %s via attribute...", - option->keyword, ppd->attrs[j]->value)); + DEBUG_printf("2_ppdOpen: Setting Default%s to %s via attribute...", option->keyword, ppd->attrs[j]->value); strlcpy(option->defchoice, ppd->attrs[j]->value, sizeof(option->defchoice)); break; @@ -1446,8 +1439,7 @@ _ppdOpen( !strcmp(ppd->attrs[j]->name + 7, name) && ppd->attrs[j]->value) { - DEBUG_printf(("2_ppdOpen: Setting Default%s to %s via attribute...", - option->keyword, ppd->attrs[j]->value)); + DEBUG_printf("2_ppdOpen: Setting Default%s to %s via attribute...", option->keyword, ppd->attrs[j]->value); strlcpy(option->defchoice, ppd->attrs[j]->value, sizeof(option->defchoice)); break; @@ -2078,8 +2070,7 @@ _ppdOpen( #ifdef DEBUG if (!cupsFileEOF(fp)) - DEBUG_printf(("1_ppdOpen: Premature EOF at %lu...\n", - (unsigned long)cupsFileTell(fp))); + DEBUG_printf("1_ppdOpen: Premature EOF at %lu...\n", (unsigned long)cupsFileTell(fp)); #endif /* DEBUG */ if (pg->ppd_status != PPD_OK) @@ -2766,8 +2757,7 @@ ppd_get_group(ppd_file_t *ppd, /* I - PPD file */ ppd_group_t *group; /* Group */ - DEBUG_printf(("7ppd_get_group(ppd=%p, name=\"%s\", text=\"%s\", cg=%p)", - ppd, name, text, pg)); + DEBUG_printf("7ppd_get_group(ppd=%p, name=\"%s\", text=\"%s\", cg=%p)", ppd, name, text, pg); for (i = ppd->num_groups, group = ppd->groups; i > 0; i --, group ++) if (!strcmp(group->name, name)) @@ -2823,8 +2813,7 @@ ppd_get_option(ppd_group_t *group, /* I - Group */ ppd_option_t *option; /* Option */ - DEBUG_printf(("7ppd_get_option(group=%p(\"%s\"), name=\"%s\")", - group, group->name, name)); + DEBUG_printf("7ppd_get_option(group=%p(\"%s\"), name=\"%s\")", group, group->name, name); for (i = group->num_options, option = group->options; i > 0; i --, option ++) if (!strcmp(option->keyword, name)) @@ -3475,9 +3464,7 @@ ppd_update_filters(ppd_file_t *ppd, /* I - PPD file */ return (0); } - DEBUG_printf(("5ppd_update_filters: srcsuper=\"%s\", srctype=\"%s\", " - "dstsuper=\"%s\", dsttype=\"%s\", cost=%d, program=\"%s\"", - srcsuper, srctype, dstsuper, dsttype, cost, program)); + DEBUG_printf("5ppd_update_filters: srcsuper=\"%s\", srctype=\"%s\", dstsuper=\"%s\", dsttype=\"%s\", cost=%d, program=\"%s\"", srcsuper, srctype, dstsuper, dsttype, cost, program); if (!strncmp(program, "maxsize(", 8) && (ptr = strchr(program + 8, ')')) != NULL) diff --git a/cups/raster-interpret.c b/cups/raster-interpret.c index f0e178abad..f25c9a22cd 100644 --- a/cups/raster-interpret.c +++ b/cups/raster-interpret.c @@ -513,8 +513,7 @@ _cupsRasterExecPS( *codeptr; /* Pointer into copy of code */ - DEBUG_printf(("_cupsRasterExecPS(h=%p, preferred_bits=%p, code=\"%s\")\n", - h, preferred_bits, code)); + DEBUG_printf("_cupsRasterExecPS(h=%p, preferred_bits=%p, code=\"%s\")\n", h, preferred_bits, code); /* * Copy the PostScript code and create a stack... diff --git a/cups/request.c b/cups/request.c index 438811f101..3c90361af7 100644 --- a/cups/request.c +++ b/cups/request.c @@ -390,8 +390,7 @@ cupsGetResponse(http_t *http, /* I - Connection to server or @code CUPS_HTTP * Wait for a response from the server... */ - DEBUG_printf(("2cupsGetResponse: Update loop, http->status=%d...", - http->status)); + DEBUG_printf("2cupsGetResponse: Update loop, http->status=%d...", http->status); do { @@ -478,9 +477,7 @@ cupsGetResponse(http_t *http, /* I - Connection to server or @code CUPS_HTTP attr = ippFindAttribute(response, "status-message", IPP_TAG_TEXT); - DEBUG_printf(("1cupsGetResponse: status-code=%s, status-message=\"%s\"", - ippErrorString(response->request.status.status_code), - attr ? attr->values[0].string.text : "")); + DEBUG_printf("1cupsGetResponse: status-code=%s, status-message=\"%s\"", ippErrorString(response->request.status.status_code), attr ? attr->values[0].string.text : ""); _cupsSetError(response->request.status.status_code, attr ? attr->values[0].string.text : @@ -653,8 +650,7 @@ cupsSendRequest(http_t *http, /* I - Connection to server or @code CUPS_HTTP } else if (http->state != HTTP_STATE_WAITING) { - DEBUG_printf(("1cupsSendRequest: Unknown HTTP state (%d), " - "reconnecting.", http->state)); + DEBUG_printf("1cupsSendRequest: Unknown HTTP state (%d), reconnecting.", http->state); if (httpReconnect2(http, 30000, NULL)) return (HTTP_STATUS_ERROR); } @@ -1139,8 +1135,7 @@ _cupsSetError(ipp_status_t status, /* I - IPP status code */ cg->last_status_message = _cupsStrAlloc(message); } - DEBUG_printf(("4_cupsSetError: last_error=%s, last_status_message=\"%s\"", - ippErrorString(cg->last_error), cg->last_status_message)); + DEBUG_printf("4_cupsSetError: last_error=%s, last_status_message=\"%s\"", ippErrorString(cg->last_error), cg->last_status_message); } @@ -1198,8 +1193,7 @@ _cupsSetHTTPError(http_status_t status) /* I - HTTP status code */ break; default : - DEBUG_printf(("4_cupsSetHTTPError: HTTP error %d mapped to " - "IPP_STATUS_ERROR_SERVICE_UNAVAILABLE!", status)); + DEBUG_printf("4_cupsSetHTTPError: HTTP error %d mapped to IPP_STATUS_ERROR_SERVICE_UNAVAILABLE!", status); _cupsSetError(IPP_STATUS_ERROR_SERVICE_UNAVAILABLE, httpStatus(status), 0); break; } diff --git a/cups/string-private.h b/cups/string-private.h index 335e579c86..e901da1e52 100644 --- a/cups/string-private.h +++ b/cups/string-private.h @@ -1,20 +1,16 @@ -/* - * Private string definitions for CUPS. - * - * Copyright © 2007-2018 by Apple Inc. - * Copyright © 1997-2006 by Easy Software Products. - * - * Licensed under Apache License v2.0. See the file "LICENSE" for more - * information. - */ +// +// Private string definitions for CUPS. +// +// Copyright © 2023 by OpenPrinting. +// Copyright © 2007-2018 by Apple Inc. +// Copyright © 1997-2006 by Easy Software Products. +// +// Licensed under Apache License v2.0. See the file "LICENSE" for more +// information. +// #ifndef _CUPS_STRING_PRIVATE_H_ # define _CUPS_STRING_PRIVATE_H_ - -/* - * Include necessary headers... - */ - # include "config.h" # include # include @@ -24,50 +20,41 @@ # include # include # include - # include - - # if defined(_WIN32) && !defined(__CUPS_SSIZE_T_DEFINED) # define __CUPS_SSIZE_T_DEFINED # include -/* Windows does not support the ssize_t type, so map it to __int64... */ -typedef __int64 ssize_t; /* @private@ */ -# endif /* _WIN32 && !__CUPS_SSIZE_T_DEFINED */ - - -/* - * C++ magic... - */ - +// Windows does not support the ssize_t type, so map it to __int64... +typedef __int64 ssize_t; // @private@ +# endif // _WIN32 && !__CUPS_SSIZE_T_DEFINED # ifdef __cplusplus extern "C" { -# endif /* __cplusplus */ +# endif // __cplusplus -/* - * String pool structures... - */ +// +// Structures... +// # define _CUPS_STR_GUARD 0x12344321 -typedef struct _cups_sp_item_s /**** String Pool Item ****/ +typedef struct _cups_sp_item_s // String Pool Item { # ifdef DEBUG_GUARDS - unsigned int guard; /* Guard word */ -# endif /* DEBUG_GUARDS */ - unsigned int ref_count; /* Reference count */ - char str[1]; /* String */ + unsigned int guard; // Guard word +# endif // DEBUG_GUARDS + unsigned int ref_count; // Reference count + char str[1]; // String } _cups_sp_item_t; -/* - * Replacements for the ctype macros that are not affected by locale, since we - * really only care about testing for ASCII characters when parsing files, etc. - * - * The _CUPS_INLINE definition controls whether we get an inline function body, - * and external function body, or an external definition. - */ +// +// Replacements for the ctype macros that are not affected by locale, since we +// really only care about testing for ASCII characters when parsing files, etc. +// +// The _CUPS_INLINE definition controls whether we get an inline function body, +// and external function body, or an external definition. +// # if defined(__GNUC__) || __STDC_VERSION__ >= 199901L # define _CUPS_INLINE static inline @@ -75,51 +62,51 @@ typedef struct _cups_sp_item_s /**** String Pool Item ****/ # define _CUPS_INLINE static __inline # elif defined(_CUPS_STRING_C_) # define _CUPS_INLINE -# endif /* __GNUC__ || __STDC_VERSION__ */ +# endif // __GNUC__ || __STDC_VERSION__ # ifdef _CUPS_INLINE -_CUPS_INLINE int /* O - 1 on match, 0 otherwise */ -_cups_isalnum(int ch) /* I - Character to test */ +_CUPS_INLINE int // O - 1 on match, 0 otherwise +_cups_isalnum(int ch) // I - Character to test { return ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')); } -_CUPS_INLINE int /* O - 1 on match, 0 otherwise */ -_cups_isalpha(int ch) /* I - Character to test */ +_CUPS_INLINE int // O - 1 on match, 0 otherwise +_cups_isalpha(int ch) // I - Character to test { return ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')); } -_CUPS_INLINE int /* O - 1 on match, 0 otherwise */ -_cups_islower(int ch) /* I - Character to test */ +_CUPS_INLINE int // O - 1 on match, 0 otherwise +_cups_islower(int ch) // I - Character to test { return (ch >= 'a' && ch <= 'z'); } -_CUPS_INLINE int /* O - 1 on match, 0 otherwise */ -_cups_isspace(int ch) /* I - Character to test */ +_CUPS_INLINE int // O - 1 on match, 0 otherwise +_cups_isspace(int ch) // I - Character to test { return (ch == ' ' || ch == '\f' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\v'); } -_CUPS_INLINE int /* O - 1 on match, 0 otherwise */ -_cups_isupper(int ch) /* I - Character to test */ +_CUPS_INLINE int // O - 1 on match, 0 otherwise +_cups_isupper(int ch) // I - Character to test { return (ch >= 'A' && ch <= 'Z'); } -_CUPS_INLINE int /* O - Converted character */ -_cups_tolower(int ch) /* I - Character to convert */ +_CUPS_INLINE int // O - Converted character +_cups_tolower(int ch) // I - Character to convert { return (_cups_isupper(ch) ? ch - 'A' + 'a' : ch); } -_CUPS_INLINE int /* O - Converted character */ -_cups_toupper(int ch) /* I - Character to convert */ +_CUPS_INLINE int // O - Converted character +_cups_toupper(int ch) // I - Character to convert { return (_cups_islower(ch) ? ch - 'a' + 'A' : ch); } @@ -131,79 +118,28 @@ extern int _cups_isspace(int ch); extern int _cups_isupper(int ch); extern int _cups_tolower(int ch); extern int _cups_toupper(int ch); -# endif /* _CUPS_INLINE */ +# endif // _CUPS_INLINE -/* - * Prototypes... - */ +// +// Functions... +// extern ssize_t _cups_safe_vsnprintf(char *buffer, size_t bufsize, const char *format, va_list args) _CUPS_PRIVATE; extern void _cups_strcpy(char *dst, const char *src) _CUPS_PRIVATE; - -# ifndef HAVE_STRDUP -extern char *_cups_strdup(const char *) _CUPS_PRIVATE; -# define strdup _cups_strdup -# endif /* !HAVE_STRDUP */ - extern int _cups_strcasecmp(const char *, const char *) _CUPS_PRIVATE; - extern int _cups_strncasecmp(const char *, const char *, size_t n) _CUPS_PRIVATE; - -# ifndef HAVE_STRLCAT -extern size_t _cups_strlcat(char *, const char *, size_t) _CUPS_PRIVATE; -# define strlcat _cups_strlcat -# endif /* !HAVE_STRLCAT */ - -# ifndef HAVE_STRLCPY -extern size_t _cups_strlcpy(char *, const char *, size_t) _CUPS_PRIVATE; -# define strlcpy _cups_strlcpy -# endif /* !HAVE_STRLCPY */ - -# ifndef HAVE_SNPRINTF -extern int _cups_snprintf(char *, size_t, const char *, ...) _CUPS_FORMAT(3, 4) _CUPS_PRIVATE; -# define snprintf _cups_snprintf -# endif /* !HAVE_SNPRINTF */ - -# ifndef HAVE_VSNPRINTF -extern int _cups_vsnprintf(char *, size_t, const char *, va_list) _CUPS_PRIVATE; -# define vsnprintf _cups_vsnprintf -# endif /* !HAVE_VSNPRINTF */ - -/* - * String pool functions... - */ - extern char *_cupsStrAlloc(const char *s) _CUPS_PRIVATE; +extern char *_cupsStrDate(char *buf, size_t bufsize, time_t timeval) _CUPS_PRIVATE; extern void _cupsStrFlush(void) _CUPS_PRIVATE; +extern char *_cupsStrFormatd(char *buf, char *bufend, double number, struct lconv *loc) _CUPS_PRIVATE; extern void _cupsStrFree(const char *s) _CUPS_PRIVATE; extern char *_cupsStrRetain(const char *s) _CUPS_PRIVATE; +extern double _cupsStrScand(const char *buf, char **bufptr, struct lconv *loc) _CUPS_PRIVATE; extern size_t _cupsStrStatistics(size_t *alloc_bytes, size_t *total_bytes) _CUPS_PRIVATE; -/* - * Floating point number functions... - */ - -extern char *_cupsStrFormatd(char *buf, char *bufend, double number, - struct lconv *loc) _CUPS_PRIVATE; -extern double _cupsStrScand(const char *buf, char **bufptr, - struct lconv *loc) _CUPS_PRIVATE; - - -/* - * Date function... - */ - -extern char *_cupsStrDate(char *buf, size_t bufsize, time_t timeval) _CUPS_PRIVATE; - - -/* - * C++ magic... - */ - # ifdef __cplusplus } -# endif /* __cplusplus */ - -#endif /* !_CUPS_STRING_H_ */ +# endif // __cplusplus +#endif // !_CUPS_STRING_H_ diff --git a/cups/string.c b/cups/string.c index 874d5d6faf..4aeef79b9c 100644 --- a/cups/string.c +++ b/cups/string.c @@ -171,9 +171,7 @@ _cupsStrAlloc(const char *s) /* I - String */ item->ref_count ++; #ifdef DEBUG_GUARDS - DEBUG_printf(("5_cupsStrAlloc: Using string %p(%s) for \"%s\", guard=%08x, " - "ref_count=%d", item, item->str, s, item->guard, - item->ref_count)); + DEBUG_printf("5_cupsStrAlloc: Using string %p(%s) for \"%s\", guard=%08x, ref_count=%d", item, item->str, s, item->guard, item->ref_count); if (item->guard != _CUPS_STR_GUARD) abort(); @@ -203,9 +201,7 @@ _cupsStrAlloc(const char *s) /* I - String */ #ifdef DEBUG_GUARDS item->guard = _CUPS_STR_GUARD; - DEBUG_printf(("5_cupsStrAlloc: Created string %p(%s) for \"%s\", guard=%08x, " - "ref_count=%d", item, item->str, s, item->guard, - item->ref_count)); + DEBUG_printf("5_cupsStrAlloc: Created string %p(%s) for \"%s\", guard=%08x, ref_count=%d", item, item->str, s, item->guard, item->ref_count); #endif /* DEBUG_GUARDS */ /* @@ -263,8 +259,7 @@ _cupsStrFlush(void) _cups_sp_item_t *item; /* Current item */ - DEBUG_printf(("4_cupsStrFlush: %d strings in array", - cupsArrayCount(stringpool))); + DEBUG_printf("4_cupsStrFlush: %d strings in array", cupsArrayCount(stringpool)); cupsMutexLock(&sp_mutex); @@ -451,8 +446,7 @@ _cupsStrRetain(const char *s) /* I - String to retain */ #ifdef DEBUG_GUARDS if (item->guard != _CUPS_STR_GUARD) { - DEBUG_printf(("5_cupsStrRetain: Retaining string %p(%s), guard=%08x, " - "ref_count=%d", item, s, item->guard, item->ref_count)); + DEBUG_printf("5_cupsStrRetain: Retaining string %p(%s), guard=%08x, ref_count=%d", item, s, item->guard, item->ref_count); abort(); } #endif /* DEBUG_GUARDS */ @@ -673,30 +667,6 @@ _cups_strcpy(char *dst, /* I - Destination string */ } -/* - * '_cups_strdup()' - Duplicate a string. - */ - -#ifndef HAVE_STRDUP -char * /* O - New string pointer */ -_cups_strdup(const char *s) /* I - String to duplicate */ -{ - char *t; /* New string pointer */ - size_t slen; /* Length of string */ - - - if (!s) - return (NULL); - - slen = strlen(s); - if ((t = malloc(slen + 1)) == NULL) - return (NULL); - - return (memcpy(t, s, slen + 1)); -} -#endif /* !HAVE_STRDUP */ - - /* * '_cups_strcasecmp()' - Do a case-insensitive comparison. */ diff --git a/cups/testcreds.c b/cups/testcreds.c index a0fc26a6b5..51eeed1549 100644 --- a/cups/testcreds.c +++ b/cups/testcreds.c @@ -1,118 +1,997 @@ -/* - * HTTP credentials test program for CUPS. - * - * Copyright 2007-2016 by Apple Inc. - * Copyright 1997-2006 by Easy Software Products. - * - * Licensed under Apache License v2.0. See the file "LICENSE" for more information. - */ - -/* - * Include necessary headers... - */ +// +// X.509 credentials test program for CUPS. +// +// Copyright © 2022-2023 by OpenPrinting. +// Copyright © 2007-2016 by Apple Inc. +// Copyright © 1997-2006 by Easy Software Products. +// +// Licensed under Apache License v2.0. See the file "LICENSE" for more +// information. +// +// Usage: testcreds [OPTIONS] [SUB-COMMAND] [ARGUMENT] +// +// Sub-Commands: +// +// ca COMMON-NAME Sign a CSR to produce a certificate. +// cacert COMMON-NAME Create a CA certificate. +// cert COMMON-NAME Create a certificate. +// client URI Connect to URI. +// csr COMMON-NAME Create a certificate signing request. +// server COMMON-NAME[:PORT] Run a HTTPS server (default port 8NNN.) +// show COMMON-NAME Show stored credentials for COMMON-NAME. +// +// Options: +// +// -C COUNTRY Set country. +// -L LOCALITY Set locality name. +// -O ORGANIZATION Set organization name. +// -R CSR-FILENAME Specify certificate signing request filename. +// -S STATE Set state. +// -U ORGANIZATIONAL-UNIT Set organizational unit name. +// -a SUBJECT-ALT-NAME Add a subjectAltName. +// -d DAYS Set expiration date in days. +// -p PURPOSE Comma-delimited certificate purpose (serverAuth, +// clientAuth, codeSigning, emailProtection, +// timeStamping, OCSPSigning) +// -r ROOT-NAME Name of root certificate +// -t TYPE Certificate type (rsa-2048, rsa-3072, rsa-4096, +// ecdsa-p256, ecdsa-p384, ecdsa-p521) +// -u USAGE Comma-delimited key usage (digitalSignature, +// nonRepudiation, keyEncipherment, +// dataEncipherment, keyAgreement, keyCertSign, +// cRLSign, encipherOnly, decipherOnly, default-ca, +// default-tls) +// #include "cups-private.h" +#include "test-internal.h" +#include +#include -/* - * 'main()' - Main entry. - */ +// +// Constants... +// -int /* O - Exit status */ -main(int argc, /* I - Number of command-line arguments */ - char *argv[]) /* I - Command-line arguments */ +#define TEST_CERT_PATH ".testssl" + + +// +// Local functions... +// + +static int do_unit_tests(void); +static int test_ca(const char *common_name, const char *csrfile, const char *root_name, int days); +static int test_cert(bool ca_cert, cups_credpurpose_t purpose, cups_credtype_t type, cups_credusage_t keyusage, const char *organization, const char *org_unit, const char *locality, const char *state, const char *country, const char *root_name, const char *common_name, size_t num_alt_names, const char **alt_names, int days); +static int test_client(const char *uri); +static int test_csr(cups_credpurpose_t purpose, cups_credtype_t type, cups_credusage_t keyusage, const char *organization, const char *org_unit, const char *locality, const char *state, const char *country, const char *common_name, size_t num_alt_names, const char **alt_names); +static int test_server(const char *host_port); +static int test_show(const char *common_name); +static int usage(FILE *fp); + + +// +// 'main()' - Main entry. +// + +int // O - Exit status +main(int argc, // I - Number of command-line arguments + char *argv[]) // I - Command-line arguments { - http_t *http; /* HTTP connection */ - char scheme[HTTP_MAX_URI], /* Scheme from URI */ - hostname[HTTP_MAX_URI], /* Hostname from URI */ - username[HTTP_MAX_URI], /* Username:password from URI */ - resource[HTTP_MAX_URI]; /* Resource from URI */ - int port; /* Port number from URI */ - http_trust_t trust; /* Trust evaluation for connection */ - cups_array_t *hcreds, /* Credentials from connection */ - *tcreds; /* Credentials from trust store */ - char hinfo[1024], /* String for connection credentials */ - tinfo[1024]; /* String for trust store credentials */ - static const char *trusts[] = /* Trust strings */ - { "OK", "Invalid", "Changed", "Expired", "Renewed", "Unknown" }; + int i; // Looping var + const char *subcommand = NULL, // Sub-command + *arg = NULL, // Argument for sub-command + *opt, // Current option character + *csrfile = NULL, // Certificste signing request filename + *root_name = NULL, // Name of root certificate + *organization = NULL, // Organization + *org_unit = NULL, // Organizational unit + *locality = NULL, // Locality + *state = NULL, // State/province + *country = NULL, // Country + *alt_names[100]; // Subject alternate names + size_t num_alt_names = 0; + int days = 365; // Days until expiration + cups_credpurpose_t purpose = CUPS_CREDPURPOSE_SERVER_AUTH; + // Certificate purpose + cups_credtype_t type = CUPS_CREDTYPE_DEFAULT; + // Certificate type + cups_credusage_t keyusage = CUPS_CREDUSAGE_DEFAULT_TLS; + // Key usage + + + // Check command-line... + for (i = 1; i < argc; i ++) + { + if (!strcmp(argv[i], "--help")) + { + return (usage(stdout)); + } + else if (!strncmp(argv[i], "--", 2)) + { + fprintf(stderr, "testcreds: Unknown option '%s'.\n", argv[i]); + return (usage(stderr)); + } + else if (argv[i][0] == '-') + { + for (opt = argv[i] + 1; *opt; opt ++) + { + switch (*opt) + { + case 'C' : // -C COUNTRY + i ++; + if (i >= argc) + { + fputs("testcreds: Missing country after '-C'.\n", stderr); + return (usage(stderr)); + } + country = argv[i]; + break; + + case 'L' : // -L LOCALITY + i ++; + if (i >= argc) + { + fputs("testcreds: Missing locality/city/town after '-L'.\n", stderr); + return (usage(stderr)); + } + locality = argv[i]; + break; + + case 'O' : // -O ORGANIZATION + i ++; + if (i >= argc) + { + fputs("testcreds: Missing organization after '-O'.\n", stderr); + return (usage(stderr)); + } + organization = argv[i]; + break; + case 'R' : // -R CSR-FILENAME + i ++; + if (i >= argc) + { + fputs("testcreds: Missing CSR filename after '-R'.\n", stderr); + return (usage(stderr)); + } + csrfile = argv[i]; + break; - /* - * Check command-line... - */ + case 'S' : // -S STATE + i ++; + if (i >= argc) + { + fputs("testcreds: Missing state/province after '-S'.\n", stderr); + return (usage(stderr)); + } + state = argv[i]; + break; + + case 'U' : // -U ORGANIZATIONAL-UNIT + i ++; + if (i >= argc) + { + fputs("testcreds: Missing organizational unit after '-U'.\n", stderr); + return (usage(stderr)); + } + org_unit = argv[i]; + break; + + case 'a' : // -a SUBJECT-ALT-NAME + i ++; + if (i >= argc) + { + fputs("testcreds: Missing subjectAltName after '-a'.\n", stderr); + return (usage(stderr)); + } + if (num_alt_names >= (sizeof(alt_names) / sizeof(alt_names[0]))) + { + fputs("testcreds: Too many subjectAltName values.\n", stderr); + return (1); + } + alt_names[num_alt_names ++] = argv[i]; + break; + + case 'd' : // -d DAYS + i ++; + if (i >= argc) + { + fputs("testcreds: Missing expiration days after '-d'.\n", stderr); + return (usage(stderr)); + } + if ((days = atoi(argv[i])) <= 0) + { + fprintf(stderr, "testcreds: Bad DAYS value '%s' after '-d'.\n", argv[i]); + return (1); + } + break; + + case 'p' : // -p PURPOSE + i ++; + if (i >= argc) + { + fputs("testcreds: Missing purpose after '-p'.\n", stderr); + return (usage(stderr)); + } + purpose = 0; + if (strstr(argv[i], "serverAuth")) + purpose |= CUPS_CREDPURPOSE_SERVER_AUTH; + if (strstr(argv[i], "clientAuth")) + purpose |= CUPS_CREDPURPOSE_CLIENT_AUTH; + if (strstr(argv[i], "codeSigning")) + purpose |= CUPS_CREDPURPOSE_CODE_SIGNING; + if (strstr(argv[i], "emailProtection")) + purpose |= CUPS_CREDPURPOSE_EMAIL_PROTECTION; + if (strstr(argv[i], "timeStamping")) + purpose |= CUPS_CREDPURPOSE_TIME_STAMPING; + if (strstr(argv[i], "OCSPSigning")) + purpose |= CUPS_CREDPURPOSE_OCSP_SIGNING; + if (purpose == 0) + { + fprintf(stderr, "testcreds: Bad purpose '%s'.\n", argv[i]); + return (usage(stderr)); + } + break; + + case 'r' : // -r ROOT-NAME + i ++; + if (i >= argc) + { + fputs("testcreds: Missing root name after '-r'.\n", stderr); + return (usage(stderr)); + } + root_name = argv[i]; + break; + + case 't' : // -t TYPE + i ++; + if (i >= argc) + { + fputs("testcreds: Missing certificate type after '-t'.\n", stderr); + return (usage(stderr)); + } + if (!strcmp(argv[i], "default")) + { + type = CUPS_CREDTYPE_DEFAULT; + } + else if (!strcmp(argv[i], "rsa-2048")) + { + type = CUPS_CREDTYPE_RSA_2048_SHA256; + } + else if (!strcmp(argv[i], "rsa-3072")) + { + type = CUPS_CREDTYPE_RSA_3072_SHA256; + } + else if (!strcmp(argv[i], "rsa-4096")) + { + type = CUPS_CREDTYPE_RSA_4096_SHA256; + } + else if (!strcmp(argv[i], "ecdsa-p256")) + { + type = CUPS_CREDTYPE_ECDSA_P256_SHA256; + } + else if (!strcmp(argv[i], "ecdsa-p384")) + { + type = CUPS_CREDTYPE_ECDSA_P384_SHA256; + } + else if (!strcmp(argv[i], "ecdsa-p521")) + { + type = CUPS_CREDTYPE_ECDSA_P521_SHA256; + } + else + { + fprintf(stderr, "testcreds: Bad certificate type '%s'.\n", argv[i]); + return (usage(stderr)); + } + break; + + case 'u' : // -u USAGE + i ++; + if (i >= argc) + { + fputs("testcreds: Missing key usage after '-u'.\n", stderr); + return (usage(stderr)); + } + keyusage = 0; + if (strstr(argv[i], "default-ca")) + keyusage = CUPS_CREDUSAGE_DEFAULT_CA; + if (strstr(argv[i], "default-tls")) + keyusage = CUPS_CREDUSAGE_DEFAULT_TLS; + if (strstr(argv[i], "digitalSignature")) + keyusage |= CUPS_CREDUSAGE_DIGITAL_SIGNATURE; + if (strstr(argv[i], "nonRepudiation")) + keyusage |= CUPS_CREDUSAGE_NON_REPUDIATION; + if (strstr(argv[i], "keyEncipherment")) + keyusage |= CUPS_CREDUSAGE_KEY_ENCIPHERMENT; + if (strstr(argv[i], "dataEncipherment")) + keyusage |= CUPS_CREDUSAGE_DATA_ENCIPHERMENT; + if (strstr(argv[i], "keyAgreement")) + keyusage |= CUPS_CREDUSAGE_KEY_AGREEMENT; + if (strstr(argv[i], "keyCertSign")) + keyusage |= CUPS_CREDUSAGE_KEY_CERT_SIGN; + if (strstr(argv[i], "cRLSign")) + keyusage |= CUPS_CREDUSAGE_CRL_SIGN; + if (strstr(argv[i], "encipherOnly")) + keyusage |= CUPS_CREDUSAGE_ENCIPHER_ONLY; + if (strstr(argv[i], "decipherOnly")) + keyusage |= CUPS_CREDUSAGE_DECIPHER_ONLY; + if (keyusage == 0) + { + fprintf(stderr, "testcreds: Bad key usage '%s'.\n", argv[i]); + return (usage(stderr)); + } + break; + + default : + fprintf(stderr, "testcreds: Unknown option '-%c'.\n", *opt); + return (usage(stderr)); + } + } + } + else if (!subcommand) + { + subcommand = argv[i]; + } + else if (!arg) + { + arg = argv[i]; + } + else + { + fprintf(stderr, "testcreds: Unknown option '%s'.\n", argv[i]); + return (usage(stderr)); + } + } - if (argc != 2) + // Make certificate directory + if (access(TEST_CERT_PATH, 0)) + mkdir(TEST_CERT_PATH, 0700); + + // Do unit tests or sub-command... + if (!subcommand) { - puts("Usage: ./testcreds hostname"); - puts(" ./testcreds https://hostname[:port]"); - return (1); + return (do_unit_tests()); + } + else if (!arg) + { + fputs("testcreds: Missing sub-command argument.\n", stderr); + return (usage(stderr)); } - if (!strncmp(argv[1], "https://", 8)) + // Run the corresponding sub-command... + if (!strcmp(subcommand, "ca")) { - /* - * Connect to the host and validate credentials... - */ + return (test_ca(arg, csrfile, root_name, days)); + } + else if (!strcmp(subcommand, "cacert")) + { + return (test_cert(true, purpose, type, keyusage, organization, org_unit, locality, state, country, root_name, arg, num_alt_names, alt_names, days)); + } + else if (!strcmp(subcommand, "cert")) + { + return (test_cert(false, purpose, type, keyusage, organization, org_unit, locality, state, country, root_name, arg, num_alt_names, alt_names, days)); + } + else if (!strcmp(subcommand, "client")) + { + return (test_client(arg)); + } + else if (!strcmp(subcommand, "csr")) + { + return (test_csr(purpose, type, keyusage, organization, org_unit, locality, state, country, arg, num_alt_names, alt_names)); + } + else if (!strcmp(subcommand, "server")) + { + return (test_server(arg)); + } + else if (!strcmp(subcommand, "show")) + { + return (test_show(arg)); + } + else + { + fprintf(stderr, "testcreds: Unknown sub-command '%s'.\n", subcommand); + return (usage(stderr)); + } +} + + +// +// 'do_unit_tests()' - Do unit tests. +// + +static int // O - Exit status +do_unit_tests(void) +{ + cups_credtype_t type; // Current credential type + char *data; // Cert data + static const char * const alt_names[] = + { // subjectAltName values + "printer.example.com", + "localhost" + }; + static const char * const types[] = + { // Credential types + "default", + "rsa-2048", + "rsa-3072", + "rsa-4096", + "ecdsa-p256", + "ecdsa-p384", + "ecdsa-p521" + }; - if (httpSeparateURI(HTTP_URI_CODING_MOST, argv[1], scheme, sizeof(scheme), username, sizeof(username), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK) + + for (type = CUPS_CREDTYPE_DEFAULT; type <= CUPS_CREDTYPE_ECDSA_P521_SHA256; type ++) + { + testBegin("cupsCreateCredentials(_site_, %s, CA)", types[type]); + if (cupsCreateCredentials(TEST_CERT_PATH, true, CUPS_CREDPURPOSE_SERVER_AUTH, type, CUPS_CREDUSAGE_DEFAULT_TLS, "Organization", "Unit", "Locality", "Ontario", "CA", "_site_", /*email*/NULL, 0, NULL, NULL, time(NULL) + 30 * 86400)) + { + testEnd(true); + + testBegin("cupsCopyCredentials(_site_)"); + data = cupsCopyCredentials(TEST_CERT_PATH, "_site_"); + testEnd(data != NULL); + free(data); + + testBegin("cupsCopyCredentialsKey(_site_)"); + data = cupsCopyCredentialsKey(TEST_CERT_PATH, "_site_"); + testEnd(data != NULL); + free(data); + } + else { - printf("ERROR: Bad URI \"%s\".\n", argv[1]); + testEndMessage(false, "%s", cupsGetErrorString()); + } + + testBegin("cupsCreateCredentials(printer w/alt names, %s, signed by CA cert)", types[type]); + if (cupsCreateCredentials(TEST_CERT_PATH, false, CUPS_CREDPURPOSE_SERVER_AUTH, type, CUPS_CREDUSAGE_DEFAULT_TLS, "Organization", "Unit", "Locality", "Ontario", "CA", "printer", "admin@example.com", sizeof(alt_names) / sizeof(alt_names[0]), alt_names, "_site_", time(NULL) + 30 * 86400)) + testEnd(true); + else + testEndMessage(false, "%s", cupsGetErrorString()); + + testBegin("cupsCreateCredentialsRequest(altprinter w/alt names, %s)", types[type]); + if (cupsCreateCredentialsRequest(TEST_CERT_PATH, CUPS_CREDPURPOSE_SERVER_AUTH, type, CUPS_CREDUSAGE_DEFAULT_TLS, "Organization", "Unit", "Locality", "Ontario", "CA", "altprinter", "admin@example.com", sizeof(alt_names) / sizeof(alt_names[0]), alt_names)) + { + testEnd(true); + + testBegin("cupsCopyCredentialsKey(altprinter w/alt names)"); + data = cupsCopyCredentialsKey(TEST_CERT_PATH, "altprinter"); + testEnd(data != NULL); + free(data); + + testBegin("cupsCopyCredentialsRequest(altprinter w/alt names)"); + data = cupsCopyCredentialsRequest(TEST_CERT_PATH, "altprinter"); + testEnd(data != NULL); + + if (data) + { + testBegin("cupsSignCredentialsRequest(altprinter w/alt names)"); + if (cupsSignCredentialsRequest(TEST_CERT_PATH, "altprinter", data, "_site_", CUPS_CREDPURPOSE_ALL, CUPS_CREDUSAGE_ALL, /*cb*/NULL, /*cb_data*/NULL, time(NULL) + 30 * 86400)) + { + testEndMessage(false, "Expected a failure"); + } + else + { + testEndMessage(true, "%s", cupsGetErrorString()); + } + + free(data); + } + } + else + { + testEndMessage(false, "%s", cupsGetErrorString()); + } + + testBegin("cupsCreateCredentialsRequest(altprinter w/o alt names, %s)", types[type]); + if (cupsCreateCredentialsRequest(TEST_CERT_PATH, CUPS_CREDPURPOSE_SERVER_AUTH, type, CUPS_CREDUSAGE_DEFAULT_TLS, "Organization", "Unit", "Locality", "Ontario", "CA", "altprinter", "admin@example.com", 0, NULL)) + { + testEnd(true); + + testBegin("cupsCopyCredentialsKey(altprinter w/o alt names)"); + data = cupsCopyCredentialsKey(TEST_CERT_PATH, "altprinter"); + testEnd(data != NULL); + free(data); + + testBegin("cupsCopyCredentialsRequest(altprinter w/o alt names)"); + data = cupsCopyCredentialsRequest(TEST_CERT_PATH, "altprinter"); + testEnd(data != NULL); + + if (data) + { + testBegin("cupsSignCredentialsRequest(altprinter w/o alt names)"); + if (cupsSignCredentialsRequest(TEST_CERT_PATH, "altprinter", data, "_site_", CUPS_CREDPURPOSE_ALL, CUPS_CREDUSAGE_ALL, /*cb*/NULL, /*cb_data*/NULL, time(NULL) + 30 * 86400)) + { + testEnd(true); + free(data); + + testBegin("cupsCopyCredentialsKey(altprinter w/o alt names)"); + data = cupsCopyCredentialsKey(TEST_CERT_PATH, "altprinter"); + testEnd(data != NULL); + } + else + { + testEndMessage(false, "%s", cupsGetErrorString()); + } + + free(data); + } + } + else + { + testEndMessage(false, "%s", cupsGetErrorString()); + } + } + + return (testsPassed ? 0 : 1); +} + + +// +// 'test_ca()' - Test generating a certificate from a CSR. +// + +static int // O - Exit status +test_ca(const char *common_name, // I - Common name + const char *csrfile, // I - CSR filename, if any + const char *root_name, // I - Root certificate name + int days) // I - Number of days +{ + char *request, // Certificate request + *cert; // Certificate + + + if (csrfile) + { + int csrfd = open(csrfile, O_RDONLY); + // File descriptor + struct stat csrinfo; // File information + + if (csrfd < 0) + { + fprintf(stderr, "testcreds: Unable to access '%s': %s\n", csrfile, strerror(errno)); return (1); } - if ((http = httpConnect2(hostname, port, NULL, AF_UNSPEC, HTTP_ENCRYPTION_ALWAYS, 1, 30000, NULL)) == NULL) + if (fstat(csrfd, &csrinfo)) { - printf("ERROR: Unable to connect to \"%s\" on port %d: %s\n", hostname, port, cupsGetErrorString()); + fprintf(stderr, "testcreds: Unable to stat '%s': %s\n", csrfile, strerror(errno)); + close(csrfd); return (1); } - puts("HTTP Credentials:"); - if (!httpCopyCredentials(http, &hcreds)) + if ((request = malloc((size_t)csrinfo.st_size + 1)) == NULL) { - trust = httpCredentialsGetTrust(hcreds, hostname); + fprintf(stderr, "testcreds: Unable to allocate memory for '%s': %s\n", csrfile, strerror(errno)); + close(csrfd); + return (1); + } - httpCredentialsString(hcreds, hinfo, sizeof(hinfo)); + if (read(csrfd, request, (size_t)csrinfo.st_size) < (ssize_t)csrinfo.st_size) + { + fprintf(stderr, "testcreds: Unable to read '%s'.\n", csrfile); + close(csrfd); + return (1); + } - printf(" Certificate Count: %d\n", cupsArrayCount(hcreds)); - if (trust == HTTP_TRUST_OK) - puts(" Trust: OK"); - else - printf(" Trust: %s (%s)\n", trusts[trust], cupsGetErrorString()); - printf(" Expiration: %s\n", httpGetDateString(httpCredentialsGetExpiration(hcreds))); - printf(" IsValidName: %d\n", httpCredentialsAreValidForName(hcreds, hostname)); - printf(" String: \"%s\"\n", hinfo); + close(csrfd); + request[csrinfo.st_size] = '\0'; + } + else if ((request = cupsCopyCredentialsRequest(TEST_CERT_PATH, common_name)) == NULL) + { + fprintf(stderr, "testcreds: No request for '%s'.\n", common_name); + return (1); + } - httpFreeCredentials(hcreds); - } + if (!cupsSignCredentialsRequest(TEST_CERT_PATH, common_name, request, root_name, CUPS_CREDPURPOSE_ALL, CUPS_CREDUSAGE_ALL, /*cb*/NULL, /*cb_data*/NULL, time(NULL) + days * 86400)) + { + fprintf(stderr, "testcreds: Unable to create certificate (%s)\n", cupsGetErrorString()); + free(request); + return (1); + } + + free(request); + + if ((cert = cupsCopyCredentials(TEST_CERT_PATH, common_name)) != NULL) + { + puts(cert); + free(cert); + } + else + { + fprintf(stderr, "testcreds: Unable to get generated certificate for '%s'.\n", common_name); + return (1); + } + + return (0); +} + + +// +// 'test_cert()' - Test creating a self-signed certificate. +// + +static int // O - Exit status +test_cert( + bool ca_cert, // I - `true` for a CA certificate, `false` for a regular one + cups_credpurpose_t purpose, // I - Certificate purpose + cups_credtype_t type, // I - Certificate type + cups_credusage_t keyusage, // I - Key usage + const char *organization, // I - Organization + const char *org_unit, // I - Organizational unit + const char *locality, // I - Locality (city/town/etc.) + const char *state, // I - State/province + const char *country, // I - Country + const char *root_name, // I - Root certificate name + const char *common_name, // I - Common name + size_t num_alt_names, // I - Number of subjectAltName's + const char **alt_names, // I - subjectAltName's + int days) // I - Number of days until expiration +{ + char *cert, // Certificate + *key; // Private key + + + if (!cupsCreateCredentials(TEST_CERT_PATH, ca_cert, purpose, type, keyusage, organization, org_unit, locality, state, country, common_name, /*email*/NULL, num_alt_names, alt_names, root_name, time(NULL) + days * 86400)) + { + fprintf(stderr, "testcreds: Unable to create certificate (%s)\n", cupsGetErrorString()); + return (1); + } + + if ((cert = cupsCopyCredentials(TEST_CERT_PATH, common_name)) != NULL) + { + puts(cert); + free(cert); + } + else + { + fprintf(stderr, "testcreds: Unable to get generated certificate for '%s'.\n", common_name); + return (1); + } + + if ((key = cupsCopyCredentialsKey(TEST_CERT_PATH, common_name)) != NULL) + { + puts(key); + free(key); + } + else + { + fprintf(stderr, "testcreds: Unable to get generated private key for '%s'.\n", common_name); + return (1); + } + + return (0); +} + + +// +// 'test_client()' - Test connecting to a HTTPS server. +// + +static int // O - Exit status +test_client(const char *uri) // I - URI +{ + http_t *http; // HTTP connection + char scheme[HTTP_MAX_URI], // Scheme from URI + hostname[HTTP_MAX_URI], // Hostname from URI + username[HTTP_MAX_URI], // Username:password from URI + resource[HTTP_MAX_URI]; // Resource from URI + int port; // Port number from URI + http_trust_t trust; // Trust evaluation for connection + char *hcreds; // Credentials from connection + char hinfo[1024], // String for connection credentials + datestr[256]; // Date string + static const char *trusts[] = // Trust strings + { "OK", "Invalid", "Changed", "Expired", "Renewed", "Unknown" }; + + + // Connect to the host and validate credentials... + if (httpSeparateURI(HTTP_URI_CODING_MOST, uri, scheme, sizeof(scheme), username, sizeof(username), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK) + { + fprintf(stderr, "testcreds: Bad URI '%s'.\n", uri); + return (1); + } + + if ((http = httpConnect2(hostname, port, NULL, AF_UNSPEC, HTTP_ENCRYPTION_ALWAYS, 1, 30000, NULL)) == NULL) + { + fprintf(stderr, "testcreds: Unable to connect to '%s' on port %d: %s\n", hostname, port, cupsGetErrorString()); + return (1); + } + + puts("TLS Server Credentials:"); + if ((hcreds = httpCopyPeerCredentials(http)) != NULL) + { + trust = cupsGetCredentialsTrust(TEST_CERT_PATH, hostname, hcreds); + + cupsGetCredentialsInfo(hcreds, hinfo, sizeof(hinfo)); + +// printf(" Certificate Count: %u\n", (unsigned)cupsArrayGetCount(hcreds)); + if (trust == HTTP_TRUST_OK) + puts(" Trust: OK"); else - puts(" Not present (error)."); + printf(" Trust: %s (%s)\n", trusts[trust], cupsGetErrorString()); + printf(" Expiration: %s\n", httpGetDateString2(cupsGetCredentialsExpiration(hcreds), datestr, sizeof(datestr))); + printf(" ValidName: %s\n", cupsAreCredentialsValidForName(hostname, hcreds) ? "true" : "false"); + printf(" Info: \"%s\"\n", hinfo); + + free(hcreds); + } + else + { + puts(" Not present (error)."); + } + + puts(""); + + return (test_show(hostname)); +} + + +// +// 'test_csr()' - Test creating a certificate signing request. +// + +static int // O - Exit status +test_csr( + cups_credpurpose_t purpose, // I - Certificate purpose + cups_credtype_t type, // I - Certificate type + cups_credusage_t keyusage, // I - Key usage + const char *organization, // I - Organization + const char *org_unit, // I - Organizational unit + const char *locality, // I - Locality (city/town/etc.) + const char *state, // I - State/province + const char *country, // I - Country + const char *common_name, // I - Common name + size_t num_alt_names, // I - Number of subjectAltName's + const char **alt_names) // I - subjectAltName's +{ + char *csr; // Certificate request + + + if (!cupsCreateCredentialsRequest(TEST_CERT_PATH, purpose, type, keyusage, organization, org_unit, locality, state, country, common_name, /*email*/NULL, num_alt_names, alt_names)) + { + fprintf(stderr, "testcreds: Unable to create certificate request (%s)\n", cupsGetErrorString()); + return (1); + } + + if ((csr = cupsCopyCredentialsRequest(TEST_CERT_PATH, common_name)) != NULL) + { + puts(csr); + free(csr); + } + else + { + fprintf(stderr, "testcreds: Unable to get generated certificate request for '%s'.\n", common_name); + return (1); + } + + return (0); +} + - puts(""); +// +// 'test_server()' - Test running a server. +// + +static int // O - Exit status +test_server(const char *host_port) // I - Hostname/port +{ + char host[256], // Hostname + *hostptr; // Pointer into hostname + int port; // Port number + nfds_t i, // Looping var + num_listeners = 0; // Number of listeners + struct pollfd listeners[2]; // Listeners + http_addr_t addr; // Listen address + http_t *http; // Client + + + // Get the host and port... + cupsCopyString(host, host_port, sizeof(host)); + if ((hostptr = strrchr(host, ':')) != NULL) + { + // Extract the port number from the argument... + *hostptr++ = '\0'; + port = atoi(hostptr); } else { - /* - * Load stored credentials... - */ + // Use the default port 8NNN where NNN is the bottom 3 digits of the UID... + port = 8000 + (int)getuid() % 1000; + } + + // Setup listeners for IPv4 and IPv6... + memset(&addr, 0, sizeof(addr)); + addr.ipv4.sin_family = AF_INET; + + if ((listeners[num_listeners].fd = httpAddrListen(&addr, port)) > 0) + { + listeners[num_listeners].events = POLLIN | POLLERR; + num_listeners ++; + } + + addr.ipv6.sin6_family = AF_INET6; + + if ((listeners[num_listeners].fd = httpAddrListen(&addr, port)) > 0) + { + listeners[num_listeners].events = POLLIN | POLLERR; + num_listeners ++; + } + + if (num_listeners == 0) + { + fprintf(stderr, "testcreds: Unable to listen on port %d: %s\n", port, cupsGetErrorString()); + return (1); + } + + printf("Listening for connections on port %d...\n", port); + + // Set certificate info... + cupsSetServerCredentials(TEST_CERT_PATH, host, true); + + // Wait for connections... + for (;;) + { + http_state_t state; // HTTP request state + char resource[1024]; // Resource path + + // Look for new connections... + if (poll(listeners, num_listeners, 1000) < 0) + { + if (errno == EINTR || errno == EAGAIN) + continue; + + perror("testcreds: Unable to poll"); + break; + } + + // Try accepting a connection... + for (i = 0, http = NULL; i < num_listeners; i ++) + { + if (listeners[i].revents & POLLIN) + { + if ((http = httpAcceptConnection(listeners[i].fd, true)) != NULL) + break; + + fprintf(stderr, "testcreds: Unable to accept connection: %s\n", cupsGetErrorString()); + } + } + + if (!http) + continue; + + // Negotiate a secure connection... + if (!httpSetEncryption(http, HTTP_ENCRYPTION_ALWAYS)) + { + fprintf(stderr, "testcreds: Unable to encrypt connection: %s\n", cupsGetErrorString()); + httpClose(http); + continue; + } + + // Process a single request and then close it out... + while ((state = httpReadRequest(http, resource, sizeof(resource))) == HTTP_STATE_WAITING) + usleep(1000); - strlcpy(hostname, argv[1], sizeof(hostname)); + if (state == HTTP_STATE_ERROR) + { + if (httpGetError(http) == EPIPE) + fputs("testcreds: Client closed connection.\n", stderr); + else + fprintf(stderr, "testcreds: Bad request line (%s).\n", strerror(httpGetError(http))); + } + else if (state == HTTP_STATE_UNKNOWN_METHOD) + { + fputs("testcreds: Bad/unknown operation.\n", stderr); + } + else if (state == HTTP_STATE_UNKNOWN_VERSION) + { + fputs("testcreds: Bad HTTP version.\n", stderr); + } + else + { + printf("%s %s\n", httpStateString(state), resource); + + if (state == HTTP_STATE_GET || state == HTTP_STATE_HEAD) + { + httpClearFields(http); + httpSetField(http, HTTP_FIELD_CONTENT_TYPE, "text/plain"); + httpSetField(http, HTTP_FIELD_CONNECTION, "close"); + httpSetLength(http, strlen(resource) + 1); + httpWriteResponse(http, HTTP_STATUS_OK); + + if (state == HTTP_STATE_GET) + { + // Echo back the resource path... + httpWrite(http, resource, strlen(resource)); + httpWrite(http, "\n", 1); + httpFlushWrite(http); + } + } + else + { + httpWriteResponse(http, HTTP_STATUS_BAD_REQUEST); + } + } + + httpClose(http); } - printf("Trust Store for \"%s\":\n", hostname); + // Close listeners and return... + for (i = 0; i < num_listeners; i ++) + httpAddrClose(&addr, listeners[i].fd); - if (!httpLoadCredentials(NULL, &tcreds, hostname)) + return (0); +} + + +// +// 'test_show()' - Test showing stored certificates. +// + +static int // O - Exit status +test_show(const char *common_name) // I - Common name +{ + char *tcreds, // Credentials from trust store + tinfo[1024], // String for trust store credentials + datestr[256]; // Date string + + + printf("Trust Store for \"%s\":\n", common_name); + + if ((tcreds = cupsCopyCredentials(TEST_CERT_PATH, common_name)) != NULL) { - httpCredentialsString(tcreds, tinfo, sizeof(tinfo)); + cupsGetCredentialsInfo(tcreds, tinfo, sizeof(tinfo)); - printf(" Certificate Count: %d\n", cupsArrayCount(tcreds)); - printf(" Expiration: %s\n", httpGetDateString(httpCredentialsGetExpiration(tcreds))); - printf(" IsValidName: %d\n", httpCredentialsAreValidForName(tcreds, hostname)); - printf(" String: \"%s\"\n", tinfo); +// printf(" Certificate Count: %u\n", (unsigned)cupsArrayGetCount(tcreds)); + printf(" Expiration: %s\n", httpGetDateString2(cupsGetCredentialsExpiration(tcreds), datestr, sizeof(datestr))); + printf(" ValidName: %s\n", cupsAreCredentialsValidForName(common_name, tcreds) ? "true" : "false"); + printf(" Info: \"%s\"\n", tinfo); - httpFreeCredentials(tcreds); + free(tcreds); } else + { puts(" Not present."); + } return (0); } + + +// +// 'usage()' - Show program usage... +// + +static int // O - Exit code +usage(FILE *fp) // I - Output file (stdout or stderr) +{ + fputs("Usage: testcreds [OPTIONS] [SUB-COMMAND] [ARGUMENT]\n", fp); + fputs("\n", fp); + fputs("Sub-Commands:\n", fp); + fputs("\n", fp); + fputs(" ca COMMON-NAME Sign a CSR to produce a certificate.\n", fp); + fputs(" cacert COMMON-NAME Create a CA certificate.\n", fp); + fputs(" cert COMMON-NAME Create a certificate.\n", fp); + fputs(" client URI Connect to URI.\n", fp); + fputs(" csr COMMON-NAME Create a certificate signing request.\n", fp); + fputs(" server COMMON-NAME[:PORT] Run a HTTPS server (default port 8NNN.)\n", fp); + fputs(" show COMMON-NAME Show stored credentials for COMMON-NAME.\n", fp); + fputs("\n", fp); + fputs("Options:\n", fp); + fputs("\n", fp); + fputs(" -C COUNTRY Set country.\n", fp); + fputs(" -L LOCALITY Set locality name.\n", fp); + fputs(" -O ORGANIZATION Set organization name.\n", fp); + fputs(" -R CSR-FILENAME Specify certificate signing request file.\n", fp); + fputs(" -S STATE Set state.\n", fp); + fputs(" -U ORGANIZATIONAL-UNIT Set organizational unit name.\n", fp); + fputs(" -a SUBJECT-ALT-NAME Add a subjectAltName.\n", fp); + fputs(" -d DAYS Set expiration date in days.\n", fp); + fputs(" -p PURPOSE Comma-delimited certificate purpose (serverAuth, clientAuth, codeSigning, emailProtection, timeStamping, OCSPSigning)\n", fp); + fputs(" -r ROOT-NAME Name of root certificate\n", fp); + fputs(" -t TYPE Certificate type (rsa-2048, rsa-3072, rsa-4096, ecdsa-p256, ecdsa-p384, ecdsa-p521)\n", fp); + fputs(" -u USAGE Comma-delimited key usage (digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign, encipherOnly, decipherOnly, default-ca, default-tls)\n", fp); + + return (fp == stderr); +} diff --git a/cups/testhttp.c b/cups/testhttp.c index bd8864031f..d3dbaf2f28 100644 --- a/cups/testhttp.c +++ b/cups/testhttp.c @@ -1,46 +1,43 @@ -/* - * HTTP test program for CUPS. - * - * Copyright © 2021-2023 by OpenPrinting. - * Copyright © 2007-2018 by Apple Inc. - * Copyright © 1997-2006 by Easy Software Products. - * - * Licensed under Apache License v2.0. See the file "LICENSE" for more - * information. - */ - -/* - * Include necessary headers... - */ +// +// HTTP test program for CUPS. +// +// Copyright © 2021-2023 by OpenPrinting. +// Copyright © 2007-2018 by Apple Inc. +// Copyright © 1997-2006 by Easy Software Products. +// +// Licensed under Apache License v2.0. See the file "LICENSE" for more +// information. +// #include "cups-private.h" +#include "test-internal.h" -/* - * Types and structures... - */ +// +// Types and structures... +// -typedef struct uri_test_s /**** URI test cases ****/ +typedef struct uri_test_s // URI test cases { - http_uri_status_t result; /* Expected return value */ - const char *uri, /* URI */ - *scheme, /* Scheme string */ - *username, /* Username:password string */ - *hostname, /* Hostname string */ - *resource; /* Resource string */ - int port, /* Port number */ - assemble_port; /* Port number for httpAssembleURI() */ - http_uri_coding_t assemble_coding;/* Coding for httpAssembleURI() */ + http_uri_status_t result; // Expected return value + const char *uri, // URI + *scheme, // Scheme string + *username, // Username:password string + *hostname, // Hostname string + *resource; // Resource string + int port, // Port number + assemble_port; // Port number for httpAssembleURI() + http_uri_coding_t assemble_coding;// Coding for httpAssembleURI() } uri_test_t; -/* - * Local globals... - */ +// +// Local globals... +// -static uri_test_t uri_tests[] = /* URI test data */ +static uri_test_t uri_tests[] = // URI test data { - /* Start with valid URIs */ + // Start with valid URIs { HTTP_URI_STATUS_OK, "file:/filename", "file", "", "", "/filename", 0, 0, HTTP_URI_CODING_MOST }, @@ -120,7 +117,7 @@ static uri_test_t uri_tests[] = /* URI test data */ "smb", "", "server", "/Some Printer", 0, 0, HTTP_URI_CODING_ALL }, - /* Missing scheme */ + // Missing scheme { HTTP_URI_STATUS_MISSING_SCHEME, "/path/to/file/index.html", "file", "", "", "/path/to/file/index.html", 0, 0, HTTP_URI_CODING_MOST }, @@ -128,12 +125,12 @@ static uri_test_t uri_tests[] = /* URI test data */ "ipp", "", "server", "/ipp", 631, 0, HTTP_URI_CODING_MOST }, - /* Unknown scheme */ + // Unknown scheme { HTTP_URI_STATUS_UNKNOWN_SCHEME, "vendor://server/resource", "vendor", "", "server", "/resource", 0, 0, HTTP_URI_CODING_MOST }, - /* Missing resource */ + // Missing resource { HTTP_URI_STATUS_MISSING_RESOURCE, "socket://[::192.168.2.1]", "socket", "", "::192.168.2.1", "/", 9100, 0, HTTP_URI_CODING_MOST }, @@ -141,12 +138,12 @@ static uri_test_t uri_tests[] = /* URI test data */ "socket", "", "192.168.1.1", "/", 9101, 0, HTTP_URI_CODING_MOST }, - /* Bad URI */ + // Bad URI { HTTP_URI_STATUS_BAD_URI, "", "", "", "", "", 0, 0, HTTP_URI_CODING_MOST }, - /* Bad scheme */ + // Bad scheme { HTTP_URI_STATUS_BAD_SCHEME, "://server/ipp", "", "", "", "", 0, 0, HTTP_URI_CODING_MOST }, @@ -154,12 +151,12 @@ static uri_test_t uri_tests[] = /* URI test data */ "", "", "", "", 0, 0, HTTP_URI_CODING_MOST }, - /* Bad username */ + // Bad username { HTTP_URI_STATUS_BAD_USERNAME, "http://username:passwor%6@server/resource", "http", "", "", "", 80, 0, HTTP_URI_CODING_MOST }, - /* Bad hostname */ + // Bad hostname { HTTP_URI_STATUS_BAD_HOSTNAME, "http://[/::1]/index.html", "http", "", "", "", 80, 0, HTTP_URI_CODING_MOST }, @@ -176,12 +173,12 @@ static uri_test_t uri_tests[] = /* URI test data */ "ipp", "", "", "", 631, 0, HTTP_URI_CODING_MOST }, - /* Bad port number */ + // Bad port number { HTTP_URI_STATUS_BAD_PORT, "http://127.0.0.1:9999a/index.html", "http", "", "127.0.0.1", "", 0, 0, HTTP_URI_CODING_MOST }, - /* Bad resource */ + // Bad resource { HTTP_URI_STATUS_BAD_RESOURCE, "mailto:\r\nbla", "mailto", "", "", "", 0, 0, HTTP_URI_CODING_MOST }, @@ -195,83 +192,78 @@ static uri_test_t uri_tests[] = /* URI test data */ static const char * const base64_tests[][2] = { { "A", "QQ==" }, - /* 010000 01 */ + // 010000 01 { "AB", "QUI=" }, - /* 010000 010100 0010 */ + // 010000 010100 0010 { "ABC", "QUJD" }, - /* 010000 010100 001001 000011 */ + // 010000 010100 001001 000011 { "ABCD", "QUJDRA==" }, - /* 010000 010100 001001 000011 010001 00 */ + // 010000 010100 001001 000011 010001 00 { "ABCDE", "QUJDREU=" }, - /* 010000 010100 001001 000011 010001 000100 0101 */ + // 010000 010100 001001 000011 010001 000100 0101 { "ABCDEF", "QUJDREVG" }, - /* 010000 010100 001001 000011 010001 000100 010101 000110 */ + // 010000 010100 001001 000011 010001 000100 010101 000110 }; -/* - * 'main()' - Main entry. - */ +// +// 'main()' - Main entry. +// -int /* O - Exit status */ -main(int argc, /* I - Number of command-line arguments */ - char *argv[]) /* I - Command-line arguments */ +int // O - Exit status +main(int argc, // I - Number of command-line arguments + char *argv[]) // I - Command-line arguments { - int i, j, k; /* Looping vars */ - http_t *http; /* HTTP connection */ - http_encryption_t encryption; /* Encryption type */ - http_status_t status; /* Status of GET command */ - int failures; /* Number of test failures */ - char buffer[8192]; /* Input buffer */ - long bytes; /* Number of bytes read */ - FILE *out; /* Output file */ - char encode[256], /* Base64-encoded string */ - decode[256]; /* Base64-decoded string */ - int decodelen; /* Length of decoded string */ - char scheme[HTTP_MAX_URI], /* Scheme from URI */ - hostname[HTTP_MAX_URI], /* Hostname from URI */ - username[HTTP_MAX_URI], /* Username:password from URI */ - resource[HTTP_MAX_URI]; /* Resource from URI */ - int port; /* Port number from URI */ - http_uri_status_t uri_status; /* Status of URI separation */ - http_addrlist_t *addrlist, /* Address list */ - *addr; /* Current address */ - off_t length, total; /* Length and total bytes */ - time_t start, current; /* Start and end time */ - const char *encoding; /* Negotiated Content-Encoding */ + int i, j, k; // Looping vars + http_t *http; // HTTP connection + http_encryption_t encryption; // Encryption type + http_status_t status; // Status of GET command + int failures; // Number of test failures + char buffer[8192]; // Input buffer + long bytes; // Number of bytes read + FILE *out; // Output file + char encode[256], // Base64-encoded string + decode[256]; // Base64-decoded string + size_t decodelen; // Length of decoded string + const char *decodeptr; // Pointer into Base64 string + char scheme[HTTP_MAX_URI], // Scheme from URI + hostname[HTTP_MAX_URI], // Hostname from URI + username[HTTP_MAX_URI], // Username:password from URI + resource[HTTP_MAX_URI]; // Resource from URI + int port; // Port number from URI + http_uri_status_t uri_status; // Status of URI separation + http_addrlist_t *addrlist, // Address list + *addr; // Current address + off_t length, total; // Length and total bytes + time_t start, current; // Start and end time + const char *encoding; // Negotiated Content-Encoding static const char * const uri_status_strings[] = - { - "HTTP_URI_STATUS_OVERFLOW", - "HTTP_URI_STATUS_BAD_ARGUMENTS", - "HTTP_URI_STATUS_BAD_RESOURCE", - "HTTP_URI_STATUS_BAD_PORT", - "HTTP_URI_STATUS_BAD_HOSTNAME", - "HTTP_URI_STATUS_BAD_USERNAME", - "HTTP_URI_STATUS_BAD_SCHEME", - "HTTP_URI_STATUS_BAD_URI", - "HTTP_URI_STATUS_OK", - "HTTP_URI_STATUS_MISSING_SCHEME", - "HTTP_URI_STATUS_UNKNOWN_SCHEME", - "HTTP_URI_STATUS_MISSING_RESOURCE" - }; - - - /* - * Do API tests if we don't have a URL on the command-line... - */ - + { // URI encode/decode status strings + "HTTP_URI_STATUS_OVERFLOW", + "HTTP_URI_STATUS_BAD_ARGUMENTS", + "HTTP_URI_STATUS_BAD_RESOURCE", + "HTTP_URI_STATUS_BAD_PORT", + "HTTP_URI_STATUS_BAD_HOSTNAME", + "HTTP_URI_STATUS_BAD_USERNAME", + "HTTP_URI_STATUS_BAD_SCHEME", + "HTTP_URI_STATUS_BAD_URI", + "HTTP_URI_STATUS_OK", + "HTTP_URI_STATUS_MISSING_SCHEME", + "HTTP_URI_STATUS_UNKNOWN_SCHEME", + "HTTP_URI_STATUS_MISSING_RESOURCE" + }; + + + // Do API tests if we don't have a URL on the command-line... if (argc == 1) { failures = 0; - /* - * httpGetDateString()/httpGetDateTime() - */ - - fputs("httpGetDateString()/httpGetDateTime(): ", stdout); + // httpGetDateString2()/httpGetDateTime() + testBegin("httpGetDateString2()/httpGetDateTime()"); start = time(NULL); - strlcpy(buffer, httpGetDateString(start), sizeof(buffer)); + httpGetDateString2(start, buffer, sizeof(buffer)); current = httpGetDateTime(buffer); i = (int)(current - start); @@ -279,31 +271,25 @@ main(int argc, /* I - Number of command-line arguments */ i = -i; if (!i) - puts("PASS"); + testEnd(true); else { failures ++; - puts("FAIL"); - printf(" Difference is %d seconds, %02d:%02d:%02d...\n", i, i / 3600, - (i / 60) % 60, i % 60); - printf(" httpGetDateString(%d) returned \"%s\"\n", (int)start, buffer); - printf(" httpGetDateTime(\"%s\") returned %d\n", buffer, (int)current); - printf(" httpGetDateString(%d) returned \"%s\"\n", (int)current, - httpGetDateString(current)); + testEnd(false); + testError("Difference is %d seconds, %02d:%02d:%02d.", i, i / 3600, (i / 60) % 60, i % 60); + testError("httpGetDateString(%d) returned \"%s\"", (int)start, buffer); + testError("httpGetDateTime(\"%s\") returned %d", buffer, (int)current); + testError("httpGetDateString2(%d) returned \"%s\"", (int)current, httpGetDateString2(current, buffer, sizeof(buffer))); } - /* - * httpDecode64_2()/httpEncode64_2() - */ - - fputs("httpDecode64_2()/httpEncode64_2(): ", stdout); + // httpDecode64_3()/httpEncode64_3() + testBegin("httpDecode64_3()/httpEncode64_3()"); for (i = 0, j = 0; i < (int)(sizeof(base64_tests) / sizeof(base64_tests[0])); i ++) { - httpEncode64_2(encode, sizeof(encode), base64_tests[i][0], - (int)strlen(base64_tests[i][0])); - decodelen = (int)sizeof(decode); - httpDecode64_2(decode, &decodelen, base64_tests[i][1]); + httpEncode64_3(encode, sizeof(encode), base64_tests[i][0], strlen(base64_tests[i][0]), false); + decodelen = sizeof(decode); + httpDecode64_3(decode, &decodelen, base64_tests[i][1], &decodeptr); if (strcmp(decode, base64_tests[i][0])) { @@ -311,12 +297,23 @@ main(int argc, /* I - Number of command-line arguments */ if (j) { - puts("FAIL"); + testEnd(false); j = 1; } - printf(" httpDecode64_2() returned \"%s\", expected \"%s\"...\n", - decode, base64_tests[i][0]); + testError("httpDecode64_3() returned \"%s\", expected \"%s\".", decode, base64_tests[i][0]); + } + else if (*decodeptr) + { + failures ++; + + if (j) + { + testEnd(false); + j = 1; + } + + testError("httpDecode64_3() returned \"%s\", expected end of string.", decodeptr); } if (strcmp(encode, base64_tests[i][1])) @@ -325,182 +322,109 @@ main(int argc, /* I - Number of command-line arguments */ if (j) { - puts("FAIL"); + testEnd(false); j = 1; } - printf(" httpEncode64_2() returned \"%s\", expected \"%s\"...\n", - encode, base64_tests[i][1]); + testError("httpEncode64_3() returned \"%s\", expected \"%s\".", encode, base64_tests[i][1]); } } if (!j) - puts("PASS"); - -#if 0 - /* - * _httpDigest() - */ - - fputs("_httpDigest(MD5): ", stdout); - if (!_httpDigest(buffer, sizeof(buffer), "MD5", "Mufasa", "http-auth@example.org", "Circle of Life", "7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", 1, "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", "auth", "GET", "/dir/index.html")) - { - failures ++; - puts("FAIL (unable to calculate hash)"); - } - else if (strcmp(buffer, "8ca523f5e9506fed4657c9700eebdbec")) - { - failures ++; - printf("FAIL (got \"%s\", expected \"8ca523f5e9506fed4657c9700eebdbec\")\n", buffer); - } - else - puts("PASS"); + testEnd(true); - fputs("_httpDigest(SHA-256): ", stdout); - if (!_httpDigest(buffer, sizeof(buffer), "SHA-256", "Mufasa", "http-auth@example.org", "Circle of Life", "7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", 1, "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ", "auth", "GET", "/dir/index.html")) - { - failures ++; - puts("FAIL (unable to calculate hash)"); - } - else if (strcmp(buffer, "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1")) - { - failures ++; - printf("FAIL (got \"%s\", expected \"753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1\")\n", buffer); - } - else - puts("PASS"); -#endif /* 0 */ - - /* - * httpGetHostname() - */ - - fputs("httpGetHostname(): ", stdout); + // httpGetHostname() + testBegin("httpGetHostname()"); if (httpGetHostname(NULL, hostname, sizeof(hostname))) - printf("PASS (%s)\n", hostname); + testEndMessage(true, "%s", hostname); else { failures ++; - puts("FAIL"); + testEnd(false); } - /* - * httpAddrGetList() - */ - - printf("httpAddrGetList(%s): ", hostname); + // httpAddrGetList() + testBegin("httpAddrGetList(%s)", hostname); addrlist = httpAddrGetList(hostname, AF_UNSPEC, NULL); if (addrlist) { for (i = 0, addr = addrlist; addr; i ++, addr = addr->next) { - char numeric[1024]; /* Numeric IP address */ + char numeric[1024]; // Numeric IP address - httpAddrString(&(addr->addr), numeric, sizeof(numeric)); + httpAddrGetString(&(addr->addr), numeric, sizeof(numeric)); if (!strcmp(numeric, "UNKNOWN")) break; } if (addr) - printf("FAIL (bad address for %s)\n", hostname); + testEndMessage(false, "bad address for %s", hostname); else - printf("PASS (%d address(es) for %s)\n", i, hostname); + testEndMessage(true, "%d address(es) for %s", i, hostname); httpAddrFreeList(addrlist); } else if (isdigit(hostname[0] & 255)) { - puts("FAIL (ignored because hostname is numeric)"); + testEndMessage(false, "ignored because hostname is numeric"); } else { failures ++; - puts("FAIL"); + testEnd(false); } - /* - * Test httpSeparateURI()... - */ - - fputs("httpSeparateURI(): ", stdout); + // Test httpSeparateURI()... + testBegin("httpSeparateURI()"); for (i = 0, j = 0; i < (int)(sizeof(uri_tests) / sizeof(uri_tests[0])); i ++) { - uri_status = httpSeparateURI(HTTP_URI_CODING_MOST, - uri_tests[i].uri, scheme, sizeof(scheme), - username, sizeof(username), - hostname, sizeof(hostname), &port, - resource, sizeof(resource)); - if (uri_status != uri_tests[i].result || - strcmp(scheme, uri_tests[i].scheme) || - strcmp(username, uri_tests[i].username) || - strcmp(hostname, uri_tests[i].hostname) || - port != uri_tests[i].port || - strcmp(resource, uri_tests[i].resource)) + uri_status = httpSeparateURI(HTTP_URI_CODING_MOST, uri_tests[i].uri, scheme, sizeof(scheme), username, sizeof(username), hostname, sizeof(hostname), &port, resource, sizeof(resource)); + if (uri_status != uri_tests[i].result || strcmp(scheme, uri_tests[i].scheme) || strcmp(username, uri_tests[i].username) || strcmp(hostname, uri_tests[i].hostname) || port != uri_tests[i].port || strcmp(resource, uri_tests[i].resource)) { failures ++; if (!j) { - puts("FAIL"); + testEnd(false); j = 1; } - printf(" \"%s\":\n", uri_tests[i].uri); + testError("\"%s\":", uri_tests[i].uri); if (uri_status != uri_tests[i].result) - printf(" Returned %s instead of %s\n", - uri_status_strings[uri_status + 8], - uri_status_strings[uri_tests[i].result + 8]); + testError(" Returned %s instead of %s", uri_status_strings[uri_status + 8], uri_status_strings[uri_tests[i].result + 8]); if (strcmp(scheme, uri_tests[i].scheme)) - printf(" Scheme \"%s\" instead of \"%s\"\n", - scheme, uri_tests[i].scheme); + testError(" Scheme \"%s\" instead of \"%s\"", scheme, uri_tests[i].scheme); if (strcmp(username, uri_tests[i].username)) - printf(" Username \"%s\" instead of \"%s\"\n", - username, uri_tests[i].username); + testError(" Username \"%s\" instead of \"%s\"", username, uri_tests[i].username); if (strcmp(hostname, uri_tests[i].hostname)) - printf(" Hostname \"%s\" instead of \"%s\"\n", - hostname, uri_tests[i].hostname); + testError(" Hostname \"%s\" instead of \"%s\"", hostname, uri_tests[i].hostname); if (port != uri_tests[i].port) - printf(" Port %d instead of %d\n", - port, uri_tests[i].port); + testError(" Port %d instead of %d", port, uri_tests[i].port); if (strcmp(resource, uri_tests[i].resource)) - printf(" Resource \"%s\" instead of \"%s\"\n", - resource, uri_tests[i].resource); + testError(" Resource \"%s\" instead of \"%s\"", resource, uri_tests[i].resource); } } if (!j) - printf("PASS (%d URIs tested)\n", - (int)(sizeof(uri_tests) / sizeof(uri_tests[0]))); - - /* - * Test httpAssembleURI()... - */ - - fputs("httpAssembleURI(): ", stdout); - for (i = 0, j = 0, k = 0; - i < (int)(sizeof(uri_tests) / sizeof(uri_tests[0])); - i ++) - if (uri_tests[i].result == HTTP_URI_STATUS_OK && - !strstr(uri_tests[i].uri, "%64") && - strstr(uri_tests[i].uri, "//")) + testEndMessage(true, "%d URIs tested", (int)(sizeof(uri_tests) / sizeof(uri_tests[0]))); + + // Test httpAssembleURI()... + testBegin("httpAssembleURI()"); + for (i = 0, j = 0, k = 0; i < (int)(sizeof(uri_tests) / sizeof(uri_tests[0])); i ++) + { + if (uri_tests[i].result == HTTP_URI_STATUS_OK && !strstr(uri_tests[i].uri, "%64") && strstr(uri_tests[i].uri, "//")) { k ++; - uri_status = httpAssembleURI(uri_tests[i].assemble_coding, - buffer, sizeof(buffer), - uri_tests[i].scheme, - uri_tests[i].username, - uri_tests[i].hostname, - uri_tests[i].assemble_port, - uri_tests[i].resource); + uri_status = httpAssembleURI(uri_tests[i].assemble_coding, buffer, sizeof(buffer), uri_tests[i].scheme, uri_tests[i].username, uri_tests[i].hostname, uri_tests[i].assemble_port, uri_tests[i].resource); if (uri_status != HTTP_URI_STATUS_OK) { @@ -508,12 +432,11 @@ main(int argc, /* I - Number of command-line arguments */ if (!j) { - puts("FAIL"); + testEnd(false); j = 1; } - printf(" \"%s\": %s\n", uri_tests[i].uri, - uri_status_strings[uri_status + 8]); + testError("\"%s\": %s", uri_tests[i].uri, uri_status_strings[uri_status + 8]); } else if (strcmp(buffer, uri_tests[i].uri)) { @@ -521,95 +444,104 @@ main(int argc, /* I - Number of command-line arguments */ if (!j) { - puts("FAIL"); + testEnd(false); j = 1; } - printf(" \"%s\": assembled = \"%s\"\n", uri_tests[i].uri, - buffer); + testError("\"%s\": assembled = \"%s\"", uri_tests[i].uri, buffer); } } + } if (!j) - printf("PASS (%d URIs tested)\n", k); + testEndMessage(true, "%d URIs tested", k); - /* - * httpAssembleUUID - */ - - fputs("httpAssembleUUID: ", stdout); - httpAssembleUUID("hostname.example.com", 631, "printer", 12345, buffer, - sizeof(buffer)); + // httpAssembleUUID + testBegin("httpAssembleUUID"); + httpAssembleUUID("hostname.example.com", 631, "printer", 12345, buffer, sizeof(buffer)); if (strncmp(buffer, "urn:uuid:", 9)) { - printf("FAIL (%s)\n", buffer); + testEndMessage(false, "%s", buffer); failures ++; } else - printf("PASS (%s)\n", buffer); - - /* - * Show a summary and return... - */ - - if (failures) - printf("\n%d TESTS FAILED!\n", failures); - else - puts("\nALL TESTS PASSED!"); + testEndMessage(true, "%s", buffer); return (failures); } else if (strstr(argv[1], "._tcp")) { - /* - * Test resolving an mDNS name. - */ - - char resolved[1024]; /* Resolved URI */ + // Test resolving an mDNS name. + char resolved[1024]; // Resolved URI + testBegin("httpResolveURI(%s, HTTP_RESOLVE_DEFAULT)", argv[1]); - printf("_httpResolveURI(%s, _HTTP_RESOLVE_DEFAULT): ", argv[1]); - fflush(stdout); - - if (!_httpResolveURI(argv[1], resolved, sizeof(resolved), - _HTTP_RESOLVE_DEFAULT, NULL, NULL)) + if (!httpResolveURI(argv[1], resolved, sizeof(resolved), HTTP_RESOLVE_DEFAULT, NULL, NULL)) { - puts("FAIL"); + testEnd(false); return (1); } else - printf("PASS (%s)\n", resolved); + testEndMessage(true, "%s", resolved); - printf("_httpResolveURI(%s, _HTTP_RESOLVE_FQDN): ", argv[1]); - fflush(stdout); + testBegin("httpResolveURI(%s, HTTP_RESOLVE_FQDN)", argv[1]); - if (!_httpResolveURI(argv[1], resolved, sizeof(resolved), - _HTTP_RESOLVE_FQDN, NULL, NULL)) + if (!httpResolveURI(argv[1], resolved, sizeof(resolved), HTTP_RESOLVE_FQDN, NULL, NULL)) { - puts("FAIL"); + testEnd(false); return (1); } else if (strstr(resolved, ".local:")) { - printf("FAIL (%s)\n", resolved); + testEndMessage(false, "%s", resolved); return (1); } else { - printf("PASS (%s)\n", resolved); + testEndMessage(true, "%s", resolved); + return (0); + } + } + else if (!strcmp(argv[1], "-d") && argc == 3) + { + // Test httpDecode64 + size_t bufsize = sizeof(buffer); + // Output size + + if (httpDecode64_3(buffer, &bufsize, argv[2], NULL)) + { + fwrite(buffer, 1, bufsize, stdout); return (0); } + + return (1); + } + else if (!strcmp(argv[1], "-e") && argc == 3) + { + // Test httpEncode64 for Base64 + if (httpEncode64_3(buffer, sizeof(buffer), argv[2], strlen(argv[2]), false)) + { + puts(buffer); + return (0); + } + + return (1); + } + else if (!strcmp(argv[1], "-E") && argc == 3) + { + // Test httpEncode64 for Base64url + if (httpEncode64_3(buffer, sizeof(buffer), argv[2], strlen(argv[2]), true)) + { + puts(buffer); + return (0); + } + + return (1); } else if (!strcmp(argv[1], "-u") && argc == 3) { - /* - * Test URI separation... - */ - - uri_status = httpSeparateURI(HTTP_URI_CODING_ALL, argv[2], scheme, - sizeof(scheme), username, sizeof(username), - hostname, sizeof(hostname), &port, - resource, sizeof(resource)); + // Test URI separation... + uri_status = httpSeparateURI(HTTP_URI_CODING_ALL, argv[2], scheme, sizeof(scheme), username, sizeof(username), hostname, sizeof(hostname), &port, resource, sizeof(resource)); printf("uri_status = %s\n", uri_status_strings[uri_status + 8]); printf("scheme = \"%s\"\n", scheme); printf("username = \"%s\"\n", username); @@ -620,10 +552,7 @@ main(int argc, /* I - Number of command-line arguments */ return (0); } - /* - * Test HTTP GET requests... - */ - + // Test HTTP GET requests... http = NULL; out = stdout; @@ -661,34 +590,35 @@ main(int argc, /* I - Number of command-line arguments */ if (httpIsEncrypted(http)) { - cups_array_t *creds; - char info[1024]; + char *creds; + char info[1024], expstr[256]; static const char *trusts[] = { "OK", "Invalid", "Changed", "Expired", "Renewed", "Unknown" }; - if (!httpCopyCredentials(http, &creds)) + if ((creds = httpCopyPeerCredentials(http)) != NULL) { - cups_array_t *lcreds; - http_trust_t trust = httpCredentialsGetTrust(creds, hostname); + char *lcreds; + http_trust_t trust = cupsGetCredentialsTrust(NULL, hostname, creds); - httpCredentialsString(creds, info, sizeof(info)); + cupsGetCredentialsInfo(creds, info, sizeof(info)); - printf("Count: %d\n", cupsArrayCount(creds)); +// printf("Count: %u\n", (unsigned)cupsArrayGetCount(creds)); printf("Trust: %s\n", trusts[trust]); - printf("Expiration: %s\n", httpGetDateString(httpCredentialsGetExpiration(creds))); - printf("IsValidName: %d\n", httpCredentialsAreValidForName(creds, hostname)); + printf("Expiration: %s\n", httpGetDateString2(cupsGetCredentialsExpiration(creds), expstr, sizeof(expstr))); + printf("IsValidName: %s\n", cupsAreCredentialsValidForName(hostname, creds) ? "true" : "false"); printf("String: \"%s\"\n", info); - printf("LoadCredentials: %d\n", httpLoadCredentials(NULL, &lcreds, hostname)); - httpCredentialsString(lcreds, info, sizeof(info)); - printf(" Count: %d\n", cupsArrayCount(lcreds)); + printf("LoadCredentials: %s\n", (lcreds = cupsCopyCredentials(NULL, hostname)) != NULL ? "true" : "false"); + cupsGetCredentialsInfo(lcreds, info, sizeof(info)); +// printf(" Count: %u\n", (unsigned)cupsArrayGetCount(lcreds)); printf(" String: \"%s\"\n", info); - if (lcreds && cupsArrayCount(creds) == cupsArrayCount(lcreds)) +#if 0 + if (lcreds && cupsArrayGetCount(creds) == cupsArrayGetCount(lcreds)) { http_credential_t *cred, *lcred; - for (i = 1, cred = (http_credential_t *)cupsArrayFirst(creds), lcred = (http_credential_t *)cupsArrayFirst(lcreds); + for (i = 1, cred = (http_credential_t *)cupsArrayGetFirst(creds), lcred = (http_credential_t *)cupsArrayGetFirst(lcreds); cred && lcred; - i ++, cred = (http_credential_t *)cupsArrayNext(creds), lcred = (http_credential_t *)cupsArrayNext(lcreds)) + i ++, cred = (http_credential_t *)cupsArrayGetNext(creds), lcred = (http_credential_t *)cupsArrayGetNext(lcreds)) { if (cred->datalen != lcred->datalen) printf(" Credential #%d: Different lengths (saved=%d, current=%d)\n", i, (int)cred->datalen, (int)lcred->datalen); @@ -698,18 +628,22 @@ main(int argc, /* I - Number of command-line arguments */ printf(" Credential #%d: Matches\n", i); } } +#endif // 0 if (trust != HTTP_TRUST_OK) { - printf("SaveCredentials: %d\n", httpSaveCredentials(NULL, creds, hostname)); - trust = httpCredentialsGetTrust(creds, hostname); + printf("SaveCredentials: %s\n", cupsSaveCredentials(NULL, hostname, creds, /*key*/NULL) ? "true" : "false"); + trust = cupsGetCredentialsTrust(NULL, hostname, creds); printf("New Trust: %s\n", trusts[trust]); } - httpFreeCredentials(creds); + free(creds); + free(lcreds); } else + { puts("No credentials!"); + } } printf("Checking file \"%s\"...\n", resource); @@ -735,17 +669,17 @@ main(int argc, /* I - Number of command-line arguments */ httpSetField(http, HTTP_FIELD_AUTHORIZATION, httpGetAuthString(http)); httpSetField(http, HTTP_FIELD_ACCEPT_LANGUAGE, "en"); - if (httpHead(http, resource)) + if (httpWriteRequest(http, "HEAD", resource)) { - if (httpReconnect2(http, 30000, NULL)) + if (!httpReconnect2(http, 30000, NULL)) { - status = HTTP_STATUS_ERROR; - break; + status = HTTP_STATUS_UNAUTHORIZED; + continue; } else { - status = HTTP_STATUS_UNAUTHORIZED; - continue; + status = HTTP_STATUS_ERROR; + break; } } @@ -755,19 +689,13 @@ main(int argc, /* I - Number of command-line arguments */ if (status == HTTP_STATUS_UNAUTHORIZED) { - /* - * Flush any error message... - */ - + // Flush any error message... httpFlush(http); - /* - * See if we can do authentication... - */ - + // See if we can do authentication... new_auth = 1; - if (cupsDoAuthentication(http, "HEAD", resource)) + if (!cupsDoAuthentication(http, "HEAD", resource)) { status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED; break; @@ -783,20 +711,20 @@ main(int argc, /* I - Number of command-line arguments */ } else if (status == HTTP_STATUS_UPGRADE_REQUIRED) { - /* Flush any error message... */ + // Flush any error message... httpFlush(http); - /* Reconnect... */ + // Reconnect... if (httpReconnect2(http, 30000, NULL)) { status = HTTP_STATUS_ERROR; break; } - /* Upgrade with encryption... */ - httpEncryption(http, HTTP_ENCRYPTION_REQUIRED); + // Upgrade with encryption... + httpSetEncryption(http, HTTP_ENCRYPTION_REQUIRED); - /* Try again, this time with encryption enabled... */ + // Try again, this time with encryption enabled... continue; } } @@ -835,17 +763,17 @@ main(int argc, /* I - Number of command-line arguments */ httpSetField(http, HTTP_FIELD_ACCEPT_LANGUAGE, "en"); httpSetField(http, HTTP_FIELD_ACCEPT_ENCODING, encoding); - if (httpGet(http, resource)) + if (httpWriteRequest(http, "GET", resource)) { - if (httpReconnect2(http, 30000, NULL)) + if (!httpReconnect2(http, 30000, NULL)) { - status = HTTP_STATUS_ERROR; - break; + status = HTTP_STATUS_UNAUTHORIZED; + continue; } else { - status = HTTP_STATUS_UNAUTHORIZED; - continue; + status = HTTP_STATUS_ERROR; + break; } } @@ -855,19 +783,13 @@ main(int argc, /* I - Number of command-line arguments */ if (status == HTTP_STATUS_UNAUTHORIZED) { - /* - * Flush any error message... - */ - + // Flush any error message... httpFlush(http); - /* - * See if we can do authentication... - */ - + // See if we can do authentication... new_auth = 1; - if (cupsDoAuthentication(http, "GET", resource)) + if (!cupsDoAuthentication(http, "GET", resource)) { status = HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED; break; @@ -883,20 +805,20 @@ main(int argc, /* I - Number of command-line arguments */ } else if (status == HTTP_STATUS_UPGRADE_REQUIRED) { - /* Flush any error message... */ + // Flush any error message... httpFlush(http); - /* Reconnect... */ + // Reconnect... if (httpReconnect2(http, 30000, NULL)) { status = HTTP_STATUS_ERROR; break; } - /* Upgrade with encryption... */ - httpEncryption(http, HTTP_ENCRYPTION_REQUIRED); + // Upgrade with encryption... + httpSetEncryption(http, HTTP_ENCRYPTION_REQUIRED); - /* Try again, this time with encryption enabled... */ + // Try again, this time with encryption enabled... continue; } } @@ -908,10 +830,10 @@ main(int argc, /* I - Number of command-line arguments */ printf("GET failed with status %d...\n", status); start = time(NULL); - length = httpGetLength2(http); + length = httpGetLength(http); total = 0; - while ((bytes = httpRead2(http, buffer, sizeof(buffer))) > 0) + while ((bytes = httpRead(http, buffer, sizeof(buffer))) > 0) { total += bytes; fwrite(buffer, (size_t)bytes, 1, out); diff --git a/cups/tlscheck.c b/cups/tlscheck.c index 15c934ef1a..dd1a90e4e5 100644 --- a/cups/tlscheck.c +++ b/cups/tlscheck.c @@ -1,62 +1,57 @@ -/* - * TLS check program for CUPS. - * - * Copyright © 2021-2023 by OpenPrinting. - * Copyright © 2007-2017 by Apple Inc. - * Copyright © 1997-2006 by Easy Software Products. - * - * Licensed under Apache License v2.0. See the file "LICENSE" for more - * information. - */ - -/* - * Include necessary headers... - */ +// +// TLS check program for CUPS. +// +// Copyright © 2021-2023 by OpenPrinting. +// Copyright © 2007-2017 by Apple Inc. +// Copyright © 1997-2006 by Easy Software Products. +// +// Licensed under Apache License v2.0. See the file "LICENSE" for more +// information. +// #include "cups-private.h" -/* - * Local functions... - */ +// +// Local functions... +// -static void usage(void) _CUPS_NORETURN; +static void usage(FILE *fp) _CUPS_NORETURN; -/* - * 'main()' - Main entry. - */ +// +// 'main()' - Main entry. +// -int /* O - Exit status */ -main(int argc, /* I - Number of command-line arguments */ - char *argv[]) /* I - Command-line arguments */ +int // O - Exit status +main(int argc, // I - Number of command-line arguments + char *argv[]) // I - Command-line arguments { - int i; /* Looping var */ - http_t *http; /* HTTP connection */ - const char *server = NULL; /* Hostname from command-line */ - int port = 0; /* Port number */ - cups_array_t *creds; /* Server credentials */ - char creds_str[2048]; /* Credentials string */ - const char *cipherName = "UNKNOWN";/* Cipher suite name */ - int dhBits = 0; /* Diffie-Hellman bits */ - int tlsVersion = 0; /* TLS version number */ - char uri[1024], /* Printer URI */ - scheme[32], /* URI scheme */ - host[256], /* Hostname */ - userpass[256], /* Username/password */ - resource[256]; /* Resource path */ - int af = AF_UNSPEC, /* Address family */ + int i; // Looping var + http_t *http = NULL; // HTTP connection + const char *server = NULL; // Hostname from command-line + int port = 0; // Port number + char *creds; // Server credentials + char creds_str[2048]; // Credentials string + const char *cipherName; // Cipher suite name + int tlsVersion = 0; // TLS version number + char uri[1024], // Printer URI + scheme[32], // URI scheme + host[256], // Hostname + userpass[256], // Username/password + resource[256]; // Resource path + int af = AF_UNSPEC, // Address family tls_options = _HTTP_TLS_NONE, - /* TLS options */ + // TLS options tls_min_version = _HTTP_TLS_1_0, tls_max_version = _HTTP_TLS_MAX, - verbose = 0; /* Verbosity */ - ipp_t *request, /* IPP Get-Printer-Attributes request */ - *response; /* IPP Get-Printer-Attributes response */ - ipp_attribute_t *attr; /* Current attribute */ - const char *name; /* Attribute name */ - char value[1024]; /* Attribute (string) value */ - static const char * const pattrs[] = /* Requested attributes */ + verbose = 0; // Verbosity + ipp_t *request, // IPP Get-Printer-Attributes request + *response; // IPP Get-Printer-Attributes response + ipp_attribute_t *attr; // Current attribute + const char *name; // Attribute name + char value[1024]; // Attribute (string) value + static const char * const pattrs[] = // Requested attributes { "color-supported", "compression-supported", @@ -78,6 +73,10 @@ main(int argc, /* I - Number of command-line arguments */ { tls_options |= _HTTP_TLS_ALLOW_DH; } + else if (!strcmp(argv[i], "--help")) + { + usage(stdout); + } else if (!strcmp(argv[i], "--no-cbc")) { tls_options |= _HTTP_TLS_DENY_CBC; @@ -124,8 +123,8 @@ main(int argc, /* I - Number of command-line arguments */ } else if (argv[i][0] == '-') { - printf("tlscheck: Unknown option '%s'.\n", argv[i]); - usage(); + fprintf(stderr, "tlscheck: Unknown option '%s'.\n", argv[i]); + usage(stderr); } else if (!server) { @@ -137,7 +136,7 @@ main(int argc, /* I - Number of command-line arguments */ else { server = argv[i]; - strlcpy(resource, "/ipp/print", sizeof(resource)); + cupsCopyString(resource, "/ipp/print", sizeof(resource)); } } else if (!port && (argv[i][0] == '=' || isdigit(argv[i][0] & 255))) @@ -149,13 +148,13 @@ main(int argc, /* I - Number of command-line arguments */ } else { - printf("tlscheck: Unexpected argument '%s'.\n", argv[i]); - usage(); + fprintf(stderr, "tlscheck: Unexpected argument '%s'.\n", argv[i]); + usage(stderr); } } if (!server) - usage(); + usage(stderr); if (!port) port = 631; @@ -170,25 +169,22 @@ main(int argc, /* I - Number of command-line arguments */ if (!http) { - printf("%s: ERROR (%s)\n", server, cupsGetErrorString()); + fprintf(stderr, "tlscheck: Unable to connect to '%s:%d': %s\n", server, port, cupsGetErrorString()); return (1); } - if (httpCopyCredentials(http, &creds)) + if ((creds = httpCopyPeerCredentials(http)) == NULL) { - strlcpy(creds_str, "Unable to get server X.509 credentials.", sizeof(creds_str)); + cupsCopyString(creds_str, "Unable to get server X.509 credentials.", sizeof(creds_str)); } else { - if (!httpCredentialsString(creds, creds_str, sizeof(creds_str))) - strlcpy(creds_str, "Unable to convert X.509 credential to string.", sizeof(creds_str)); - httpFreeCredentials(creds); + if (!cupsGetCredentialsInfo(creds, creds_str, sizeof(creds_str))) + cupsCopyString(creds_str, "Unable to convert X.509 credential to string.", sizeof(creds_str)); + free(creds); } #ifdef HAVE_OPENSSL - int cipherBits; // Encryption key bits - char cipherStr[1024]; // Combined cipher name - switch (SSL_version(http->tls)) { default : @@ -214,548 +210,31 @@ main(int argc, /* I - Number of command-line arguments */ # endif // TLS1_3_VERSION } - snprintf(cipherStr, sizeof(cipherStr), "%s_%dbits", SSL_get_cipher_name(http->tls), SSL_get_cipher_bits(http->tls, &cipherBits)); - - cipherName = cipherStr; - -#elif defined(HAVE_GNUTLS) -#elif defined(__APPLE__) - SSLProtocol protocol; - SSLCipherSuite cipher; - char unknownCipherName[256]; - int paramsNeeded = 0; - const void *params; - size_t paramsLen; - OSStatus err; - - if ((err = SSLGetNegotiatedProtocolVersion(http->tls, &protocol)) != noErr) - { - printf("%s: ERROR (No protocol version - %d)\n", server, (int)err); - httpClose(http); - return (1); - } + cipherName = SSL_get_cipher_name(http->tls); - switch (protocol) +#else // HAVE_GNUTLS + switch (gnutls_protocol_get_version(http->tls)) { default : tlsVersion = 0; break; - case kSSLProtocol3 : - tlsVersion = 30; - break; - case kTLSProtocol1 : + case GNUTLS_TLS1_0 : tlsVersion = 10; break; - case kTLSProtocol11 : + case GNUTLS_TLS1_1 : tlsVersion = 11; break; - case kTLSProtocol12 : + case GNUTLS_TLS1_2 : tlsVersion = 12; break; - } - - if ((err = SSLGetNegotiatedCipher(http->tls, &cipher)) != noErr) - { - printf("%s: ERROR (No cipher suite - %d)\n", server, (int)err); - httpClose(http); - return (1); - } - - switch (cipher) - { - case TLS_NULL_WITH_NULL_NULL: - cipherName = "TLS_NULL_WITH_NULL_NULL"; - break; - case TLS_RSA_WITH_NULL_MD5: - cipherName = "TLS_RSA_WITH_NULL_MD5"; - break; - case TLS_RSA_WITH_NULL_SHA: - cipherName = "TLS_RSA_WITH_NULL_SHA"; - break; - case TLS_RSA_WITH_RC4_128_MD5: - cipherName = "TLS_RSA_WITH_RC4_128_MD5"; - break; - case TLS_RSA_WITH_RC4_128_SHA: - cipherName = "TLS_RSA_WITH_RC4_128_SHA"; - break; - case TLS_RSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; - break; - case TLS_RSA_WITH_NULL_SHA256: - cipherName = "TLS_RSA_WITH_NULL_SHA256"; - break; - case TLS_RSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_RSA_WITH_AES_128_CBC_SHA256"; - break; - case TLS_RSA_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_RSA_WITH_AES_256_CBC_SHA256"; - break; - case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_DSS_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_DSS_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_RC4_128_MD5: - cipherName = "TLS_DH_anon_WITH_RC4_128_MD5"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DH_anon_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_256_CBC_SHA256: - cipherName = "TLS_DH_anon_WITH_AES_256_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_PSK_WITH_RC4_128_SHA: - cipherName = "TLS_PSK_WITH_RC4_128_SHA"; - break; - case TLS_PSK_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_PSK_WITH_3DES_EDE_CBC_SHA"; - break; - case TLS_PSK_WITH_AES_128_CBC_SHA: - cipherName = "TLS_PSK_WITH_AES_128_CBC_SHA"; - break; - case TLS_PSK_WITH_AES_256_CBC_SHA: - cipherName = "TLS_PSK_WITH_AES_256_CBC_SHA"; - break; - case TLS_DHE_PSK_WITH_RC4_128_SHA: - cipherName = "TLS_DHE_PSK_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_RSA_PSK_WITH_RC4_128_SHA: - cipherName = "TLS_RSA_PSK_WITH_RC4_128_SHA"; - break; - case TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"; - break; - case TLS_RSA_PSK_WITH_AES_128_CBC_SHA: - cipherName = "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"; - break; - case TLS_RSA_PSK_WITH_AES_256_CBC_SHA: - cipherName = "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"; - break; - case TLS_PSK_WITH_NULL_SHA: - cipherName = "TLS_PSK_WITH_NULL_SHA"; - break; - case TLS_DHE_PSK_WITH_NULL_SHA: - cipherName = "TLS_DHE_PSK_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_RSA_PSK_WITH_NULL_SHA: - cipherName = "TLS_RSA_PSK_WITH_NULL_SHA"; - break; - case TLS_RSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_RSA_WITH_AES_128_GCM_SHA256"; - break; - case TLS_RSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_RSA_WITH_AES_256_GCM_SHA384"; - break; - case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_DH_DSS_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_DSS_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DH_anon_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DH_anon_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_PSK_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_PSK_WITH_AES_128_GCM_SHA256"; - break; - case TLS_PSK_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_PSK_WITH_AES_256_GCM_SHA384"; - break; - case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"; - break; - case TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"; - break; - case TLS_PSK_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_PSK_WITH_AES_128_CBC_SHA256"; - break; - case TLS_PSK_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_PSK_WITH_AES_256_CBC_SHA384"; - break; - case TLS_PSK_WITH_NULL_SHA256: - cipherName = "TLS_PSK_WITH_NULL_SHA256"; - break; - case TLS_PSK_WITH_NULL_SHA384: - cipherName = "TLS_PSK_WITH_NULL_SHA384"; - break; - case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_NULL_SHA256: - cipherName = "TLS_DHE_PSK_WITH_NULL_SHA256"; - paramsNeeded = 1; - break; - case TLS_DHE_PSK_WITH_NULL_SHA384: - cipherName = "TLS_DHE_PSK_WITH_NULL_SHA384"; - paramsNeeded = 1; - break; - case TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"; - break; - case TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"; - break; - case TLS_RSA_PSK_WITH_NULL_SHA256: - cipherName = "TLS_RSA_PSK_WITH_NULL_SHA256"; - break; - case TLS_RSA_PSK_WITH_NULL_SHA384: - cipherName = "TLS_RSA_PSK_WITH_NULL_SHA384"; - break; - case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: - cipherName = "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: - cipherName = "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: - cipherName = "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: - cipherName = "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"; - paramsNeeded = 1; - break; - case TLS_RSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_RSA_WITH_AES_128_CBC_SHA"; - break; - case TLS_DH_DSS_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DH_DSS_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DH_RSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_128_CBC_SHA: - cipherName = "TLS_DH_anon_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_RSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_RSA_WITH_AES_256_CBC_SHA"; - break; - case TLS_DH_DSS_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DH_DSS_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_RSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DH_RSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_DH_anon_WITH_AES_256_CBC_SHA: - cipherName = "TLS_DH_anon_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_NULL_SHA: - cipherName = "TLS_ECDH_ECDSA_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: - cipherName = "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_NULL_SHA: - cipherName = "TLS_ECDHE_ECDSA_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: - cipherName = "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_NULL_SHA: - cipherName = "TLS_ECDH_RSA_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_RC4_128_SHA: - cipherName = "TLS_ECDH_RSA_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_NULL_SHA: - cipherName = "TLS_ECDHE_RSA_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_RC4_128_SHA: - cipherName = "TLS_ECDHE_RSA_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: - cipherName = "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: - cipherName = "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_anon_WITH_NULL_SHA: - cipherName = "TLS_ECDH_anon_WITH_NULL_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_anon_WITH_RC4_128_SHA: - cipherName = "TLS_ECDH_anon_WITH_RC4_128_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: - cipherName = "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_anon_WITH_AES_128_CBC_SHA: - cipherName = "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"; - paramsNeeded = 1; - break; - case TLS_ECDH_anon_WITH_AES_256_CBC_SHA: - cipherName = "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"; - paramsNeeded = 1; - break; - default : - snprintf(unknownCipherName, sizeof(unknownCipherName), "UNKNOWN_%04X", cipher); - cipherName = unknownCipherName; + case GNUTLS_TLS1_3 : + tlsVersion = 13; break; } + cipherName = gnutls_session_get_desc(http->tls); +#endif // HAVE_OPENSSL - if (cipher == TLS_RSA_WITH_RC4_128_MD5 || - cipher == TLS_RSA_WITH_RC4_128_SHA) - { - printf("%s: ERROR (Printers MUST NOT negotiate RC4 cipher suites.)\n", server); - httpClose(http); - return (1); - } - - if ((err = SSLGetDiffieHellmanParams(http->tls, ¶ms, ¶msLen)) != noErr && paramsNeeded) - { - printf("%s: ERROR (Unable to get Diffie-Hellman parameters - %d)\n", server, (int)err); - httpClose(http); - return (1); - } - - if (paramsLen < 128 && paramsLen != 0) - { - printf("%s: ERROR (Diffie-Hellman parameters MUST be at least 2048 bits, but Printer uses only %d bits/%d bytes)\n", server, (int)paramsLen * 8, (int)paramsLen); - httpClose(http); - return (1); - } - - dhBits = (int)paramsLen * 8; -#endif /* HAVE_OPENSSL */ - - if (dhBits > 0) - printf("%s: OK (TLS: %d.%d, %s, %d DH bits)\n", server, tlsVersion / 10, tlsVersion % 10, cipherName, dhBits); - else - printf("%s: OK (TLS: %d.%d, %s)\n", server, tlsVersion / 10, tlsVersion % 10, cipherName); - + printf("%s: OK (TLS: %d.%d, %s)\n", server, tlsVersion / 10, tlsVersion % 10, cipherName); printf(" %s\n", creds_str); if (verbose) @@ -790,31 +269,32 @@ main(int argc, /* I - Number of command-line arguments */ } -/* - * 'usage()' - Show program usage. - */ +// +// 'usage()' - Show program usage. +// static void -usage(void) +usage(FILE *fp) // I - Output file { - puts("Usage: ./tlscheck [options] server [port]"); - puts(" ./tlscheck [options] ipps://server[:port]/path"); - puts(""); - puts("Options:"); - puts(" --dh Allow DH/DHE key exchange"); - puts(" --no-cbc Disable CBC cipher suites"); - puts(" --no-tls10 Disable TLS/1.0"); - puts(" --rc4 Allow RC4 encryption"); - puts(" --tls10 Only use TLS/1.0"); - puts(" --tls11 Only use TLS/1.1"); - puts(" --tls12 Only use TLS/1.2"); - puts(" --tls13 Only use TLS/1.3"); - puts(" --verbose Be verbose"); - puts(" -4 Connect using IPv4 addresses only"); - puts(" -6 Connect using IPv6 addresses only"); - puts(" -v Be verbose"); - puts(""); - puts("The default port is 631."); - - exit(1); + fputs("Usage: ./tlscheck [OPTIONS] SERVER [PORT]\n", fp); + fputs(" ./tlscheck [OPTIONS] ipps://SERVER[:PORT]/PATH\n", fp); + fputs("\n", fp); + fputs("Options:\n", fp); + fputs(" --dh Allow DH/DHE key exchange\n", fp); + fputs(" --help Show help\n", fp); + fputs(" --no-cbc Disable CBC cipher suites\n", fp); + fputs(" --no-tls10 Disable TLS/1.0\n", fp); + fputs(" --rc4 Allow RC4 encryption\n", fp); + fputs(" --tls10 Only use TLS/1.0\n", fp); + fputs(" --tls11 Only use TLS/1.1\n", fp); + fputs(" --tls12 Only use TLS/1.2\n", fp); + fputs(" --tls13 Only use TLS/1.3\n", fp); + fputs(" --verbose Be verbose\n", fp); + fputs(" -4 Connect using IPv4 addresses only\n", fp); + fputs(" -6 Connect using IPv6 addresses only\n", fp); + fputs(" -v Be verbose\n", fp); + fputs("\n", fp); + fputs("The default port is 631.\n", fp); + + exit(fp == stderr); } diff --git a/cups/transcode.c b/cups/transcode.c index 096c9aa28e..28755f4e1a 100644 --- a/cups/transcode.c +++ b/cups/transcode.c @@ -410,8 +410,7 @@ cupsUTF8ToUTF32( *dest++ = ch32; - DEBUG_printf(("4cupsUTF8ToUTF32: %02x %02x => %08X", - src[-2], src[-1], (unsigned)ch32)); + DEBUG_printf("4cupsUTF8ToUTF32: %02x %02x => %08X", src[-2], src[-1], (unsigned)ch32); } else if ((ch & 0xf0) == 0xe0) { @@ -452,8 +451,7 @@ cupsUTF8ToUTF32( *dest++ = ch32; - DEBUG_printf(("4cupsUTF8ToUTF32: %02x %02x %02x => %08X", - src[-3], src[-2], src[-1], (unsigned)ch32)); + DEBUG_printf("4cupsUTF8ToUTF32: %02x %02x %02x => %08X", src[-3], src[-2], src[-1], (unsigned)ch32); } else if ((ch & 0xf8) == 0xf0) { @@ -504,8 +502,7 @@ cupsUTF8ToUTF32( *dest++ = ch32; - DEBUG_printf(("4cupsUTF8ToUTF32: %02x %02x %02x %02x => %08X", - src[-4], src[-3], src[-2], src[-1], (unsigned)ch32)); + DEBUG_printf("4cupsUTF8ToUTF32: %02x %02x %02x %02x => %08X", src[-4], src[-3], src[-2], src[-1], (unsigned)ch32); } else { @@ -649,8 +646,7 @@ cupsUTF32ToUTF8( *dest++ = (cups_utf8_t)(0x80 | (ch & 0x3f)); i -= 2; - DEBUG_printf(("4cupsUTF32ToUTF8: %08x => %02x %02x", (unsigned)ch, - dest[-2], dest[-1])); + DEBUG_printf("4cupsUTF32ToUTF8: %08x => %02x %02x", (unsigned)ch, dest[-2], dest[-1]); } else if (ch < 0x10000) { @@ -670,8 +666,7 @@ cupsUTF32ToUTF8( *dest++ = (cups_utf8_t)(0x80 | (ch & 0x3f)); i -= 3; - DEBUG_printf(("4cupsUTF32ToUTF8: %08x => %02x %02x %02x", (unsigned)ch, - dest[-3], dest[-2], dest[-1])); + DEBUG_printf("4cupsUTF32ToUTF8: %08x => %02x %02x %02x", (unsigned)ch, dest[-3], dest[-2], dest[-1]); } else { @@ -692,8 +687,7 @@ cupsUTF32ToUTF8( *dest++ = (cups_utf8_t)(0x80 | (ch & 0x3f)); i -= 4; - DEBUG_printf(("4cupsUTF32ToUTF8: %08x => %02x %02x %02x %02x", - (unsigned)ch, dest[-4], dest[-3], dest[-2], dest[-1])); + DEBUG_printf("4cupsUTF32ToUTF8: %08x => %02x %02x %02x %02x", (unsigned)ch, dest[-4], dest[-3], dest[-2], dest[-1]); } } diff --git a/scheduler/ipp.c b/scheduler/ipp.c index 4153569382..ab2e749e6d 100644 --- a/scheduler/ipp.c +++ b/scheduler/ipp.c @@ -5320,7 +5320,7 @@ create_local_bg_thread( { cupsdLogMessage(CUPSD_LOG_DEBUG2, "%s: Resolving mDNS URI \"%s\".", printer->name, printer->device_uri); - if (!_httpResolveURI(printer->device_uri, uri, sizeof(uri), _HTTP_RESOLVE_DEFAULT, NULL, NULL)) + if (!httpResolveURI(printer->device_uri, uri, sizeof(uri), HTTP_RESOLVE_DEFAULT, NULL, NULL)) { cupsdLogMessage(CUPSD_LOG_ERROR, "%s: Couldn't resolve mDNS URI \"%s\".", printer->name, printer->device_uri); return (NULL); diff --git a/scheduler/testspeed.c b/scheduler/testspeed.c index bcf63282b0..22656cd913 100644 --- a/scheduler/testspeed.c +++ b/scheduler/testspeed.c @@ -64,7 +64,7 @@ main(int argc, /* I - Number of command-line arguments */ children = 5; server = (char *)cupsServer(); port = ippPort(); - encryption = HTTP_ENCRYPT_IF_REQUESTED; + encryption = HTTP_ENCRYPTION_IF_REQUESTED; verbose = 0; opstring = NULL; @@ -75,7 +75,7 @@ main(int argc, /* I - Number of command-line arguments */ switch (*ptr) { case 'E' : /* Enable encryption */ - encryption = HTTP_ENCRYPT_REQUIRED; + encryption = HTTP_ENCRYPTION_REQUIRED; break; case 'c' : /* Number of children */ @@ -130,7 +130,7 @@ main(int argc, /* I - Number of command-line arguments */ { printf("testspeed: Simulating %d clients with %d requests to %s with " "%sencryption...\n", children, requests, server, - encryption == HTTP_ENCRYPT_IF_REQUESTED ? "no " : ""); + encryption == HTTP_ENCRYPTION_IF_REQUESTED ? "no " : ""); } start = time(NULL); @@ -156,7 +156,7 @@ main(int argc, /* I - Number of command-line arguments */ strlcpy(options, "-cr", sizeof(options)); - if (encryption == HTTP_ENCRYPT_REQUIRED) + if (encryption == HTTP_ENCRYPTION_REQUIRED) strlcat(options, "E", sizeof(options)); if (verbose) diff --git a/scheduler/testsub.c b/scheduler/testsub.c index c11d5e187b..d7cc386d3c 100644 --- a/scheduler/testsub.c +++ b/scheduler/testsub.c @@ -65,7 +65,7 @@ main(int argc, /* I - Number of command-line arguments */ for (i = 1; i < argc; i ++) if (!strcmp(argv[i], "-E")) - cupsSetEncryption(HTTP_ENCRYPT_REQUIRED); + cupsSetEncryption(HTTP_ENCRYPTION_REQUIRED); else if (!strcmp(argv[i], "-e")) { i ++;