KMF_RETURN genkeypair_file(KMF_HANDLE_T kmfhandle, KMF_KEY_ALG keyAlg, int keylen, KMF_ENCODE_FORMAT fmt, char *outkey, KMF_KEY_HANDLE *outPriKey, KMF_KEY_HANDLE *outPubKey) { KMF_RETURN kmfrv; KMF_KEY_HANDLE pubk, prik; char *fullkeypath = NULL; KMF_KEYSTORE_TYPE kstype = KMF_KEYSTORE_OPENSSL; KMF_ATTRIBUTE attrlist[10]; int numattr = 0; KMF_KEY_ALG keytype; uint32_t keylength; KMF_ENCODE_FORMAT format; if (EMPTYSTRING(outkey)) { cryptoerror(LOG_STDERR, gettext("No output file was specified for " "the key\n")); return (PK_ERR_USAGE); } fullkeypath = strdup(outkey); if (verify_file(fullkeypath)) { cryptoerror(LOG_STDERR, gettext("Cannot write the indicated output " "key file (%s).\n"), fullkeypath); free(fullkeypath); return (PK_ERR_USAGE); } keylength = keylen; /* bits */ keytype = keyAlg; format = fmt; kmf_set_attr_at_index(attrlist, numattr, KMF_KEYSTORE_TYPE_ATTR, &kstype, sizeof (kstype)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_KEYALG_ATTR, &keytype, sizeof (keytype)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_KEYLENGTH_ATTR, &keylength, sizeof (keylength)); numattr++; if (fullkeypath != NULL) { kmf_set_attr_at_index(attrlist, numattr, KMF_KEY_FILENAME_ATTR, fullkeypath, strlen(fullkeypath)); numattr++; } kmf_set_attr_at_index(attrlist, numattr, KMF_ENCODE_FORMAT_ATTR, &format, sizeof (format)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_PRIVKEY_HANDLE_ATTR, &prik, sizeof (KMF_KEY_HANDLE)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_PUBKEY_HANDLE_ATTR, &pubk, sizeof (KMF_KEY_HANDLE)); numattr++; kmfrv = kmf_create_keypair(kmfhandle, numattr, attrlist); if (kmfrv != KMF_OK) { goto cleanup; } cleanup: if (fullkeypath != NULL) free(fullkeypath); if (kmfrv == KMF_OK) { if (outPriKey != NULL) *outPriKey = prik; if (outPubKey != NULL) *outPubKey = pubk; } return (kmfrv); }
int pk_genkeypair(int argc, char *argv[]) { int rv; int opt; extern int optind_av; extern char *optarg_av; KMF_KEYSTORE_TYPE kstype = 0; char *tokenname = NULL; char *dir = NULL; char *prefix = NULL; char *keytype = PK_DEFAULT_KEYTYPE; int keylen = PK_DEFAULT_KEYLENGTH; char *label = NULL; char *outkey = NULL; char *format = NULL; KMF_HANDLE_T kmfhandle = NULL; KMF_ENCODE_FORMAT fmt = KMF_FORMAT_ASN1; KMF_KEY_ALG keyAlg = KMF_RSA; KMF_ALGORITHM_INDEX sigAlg; KMF_CREDENTIAL tokencred = {NULL, 0}; KMF_OID *curveoid = NULL; /* ECC */ int y_flag = 0; while ((opt = getopt_av(argc, argv, "k:(keystore)s:(subject)n:(nickname)" "T:(token)d:(dir)p:(prefix)t:(keytype)y:(keylen)" "l:(label)K:(outkey)F:(format)C:(curve)" "E(listcurves)")) != EOF) { if (opt != 'i' && opt != 'E' && EMPTYSTRING(optarg_av)) return (PK_ERR_USAGE); switch (opt) { case 'k': kstype = KS2Int(optarg_av); if (kstype == 0) return (PK_ERR_USAGE); break; case 'l': case 'n': if (label) return (PK_ERR_USAGE); label = optarg_av; break; case 'T': if (tokenname) return (PK_ERR_USAGE); tokenname = optarg_av; break; case 'd': if (dir) return (PK_ERR_USAGE); dir = optarg_av; break; case 'p': if (prefix) return (PK_ERR_USAGE); prefix = optarg_av; break; case 't': keytype = optarg_av; break; case 'y': if (sscanf(optarg_av, "%d", &keylen) != 1) { cryptoerror(LOG_STDERR, gettext("key length must be" "a numeric value (%s)\n"), optarg_av); return (PK_ERR_USAGE); } y_flag++; break; case 'K': if (outkey) return (PK_ERR_USAGE); outkey = optarg_av; break; case 'F': if (format) return (PK_ERR_USAGE); format = optarg_av; break; case 'C': curveoid = ecc_name_to_oid(optarg_av); if (curveoid == NULL) { cryptoerror(LOG_STDERR, gettext( "Unrecognized ECC curve.\n")); return (PK_ERR_USAGE); } break; case 'E': show_ecc_curves(); return (0); default: return (PK_ERR_USAGE); } } /* No additional args allowed. */ argc -= optind_av; argv += optind_av; if (argc) { return (PK_ERR_USAGE); } if ((rv = kmf_initialize(&kmfhandle, NULL, NULL)) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Error initializing KMF\n")); return (PK_ERR_USAGE); } /* Assume keystore = PKCS#11 if not specified. */ if (kstype == 0) kstype = KMF_KEYSTORE_PK11TOKEN; DIR_OPTION_CHECK(kstype, dir); if (format && (fmt = Str2Format(format)) == KMF_FORMAT_UNDEF) { cryptoerror(LOG_STDERR, gettext("Error parsing format string (%s).\n"), format); return (PK_ERR_USAGE); } if (Str2KeyType(keytype, NULL, &keyAlg, &sigAlg) != 0) { cryptoerror(LOG_STDERR, gettext("Unrecognized keytype (%s).\n"), keytype); return (PK_ERR_USAGE); } if (curveoid != NULL && keyAlg != KMF_ECDSA) { cryptoerror(LOG_STDERR, gettext("EC curves are only " "valid for EC keytypes.\n")); return (PK_ERR_USAGE); } if (keyAlg == KMF_ECDSA && curveoid == NULL) { cryptoerror(LOG_STDERR, gettext("A curve must be " "specifed when using EC keys.\n")); return (PK_ERR_USAGE); } if (keyAlg == KMF_ECDSA && kstype == KMF_KEYSTORE_OPENSSL) { (void) fprintf(stderr, gettext("ECC certificates are" "only supported with the pkcs11 and nss keystores\n")); rv = PK_ERR_USAGE; goto end; } /* Adjust default keylength for NSS and DSA */ if (keyAlg == KMF_DSA && kstype == KMF_KEYSTORE_NSS) { /* NSS only allows for 512-1024 bit DSA keys */ if (!y_flag) /* If nothing was given, default to 1024 */ keylen = 1024; else if (keylen > 1024 || keylen < 512) { (void) fprintf(stderr, gettext("NSS keystore only " "supports DSA keylengths of 512 - 1024 bits\n")); rv = PK_ERR_USAGE; goto end; } } if (kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN) { if (label == NULL) { (void) fprintf(stderr, gettext("No key label specified\n")); rv = PK_ERR_USAGE; goto end; } if (tokenname == NULL || !strlen(tokenname)) { if (kstype == KMF_KEYSTORE_NSS) { tokenname = "internal"; } else { tokenname = PK_DEFAULT_PK11TOKEN; } } (void) get_token_password(kstype, tokenname, &tokencred); } if (kstype == KMF_KEYSTORE_NSS) { if (dir == NULL) dir = PK_DEFAULT_DIRECTORY; rv = genkeypair_nss(kmfhandle, tokenname, label, dir, prefix, keyAlg, keylen, &tokencred, curveoid, NULL, NULL); } else if (kstype == KMF_KEYSTORE_PK11TOKEN) { rv = genkeypair_pkcs11(kmfhandle, tokenname, label, keyAlg, keylen, &tokencred, curveoid, NULL, NULL); } else if (kstype == KMF_KEYSTORE_OPENSSL) { rv = genkeypair_file(kmfhandle, keyAlg, keylen, fmt, outkey, NULL, NULL); } if (rv != KMF_OK) display_error(kmfhandle, rv, gettext("Error creating and keypair")); end: if (tokencred.cred != NULL) free(tokencred.cred); (void) kmf_finalize(kmfhandle); return (rv); }
static KMF_RETURN gencsr_file(KMF_HANDLE_T kmfhandle, KMF_KEY_ALG keyAlg, int keylen, KMF_ENCODE_FORMAT fmt, char *subject, char *altname, KMF_GENERALNAMECHOICES alttype, int altcrit, uint16_t kubits, int kucrit, char *outcsr, char *outkey, EKU_LIST *ekulist, KMF_ALGORITHM_INDEX sigAlg) { KMF_RETURN kmfrv; KMF_KEY_HANDLE pubk, prik; KMF_X509_NAME csrSubject; KMF_CSR_DATA csr; KMF_DATA signedCsr = {NULL, 0}; char *fullcsrpath = NULL; char *fullkeypath = NULL; (void) memset(&csr, 0, sizeof (csr)); (void) memset(&csrSubject, 0, sizeof (csrSubject)); if (EMPTYSTRING(outcsr) || EMPTYSTRING(outkey)) { cryptoerror(LOG_STDERR, gettext("No output file was specified for " "the csr or key\n")); return (KMF_ERR_BAD_PARAMETER); } fullcsrpath = strdup(outcsr); if (verify_file(fullcsrpath)) { cryptoerror(LOG_STDERR, gettext("Cannot write the indicated output " "certificate file (%s).\n"), fullcsrpath); free(fullcsrpath); return (PK_ERR_USAGE); } /* If the subject name cannot be parsed, flag it now and exit */ if ((kmfrv = kmf_dn_parser(subject, &csrSubject)) != KMF_OK) { return (kmfrv); } /* * Share the "genkeypair" routine for creating the keypair. */ kmfrv = genkeypair_file(kmfhandle, keyAlg, keylen, fmt, outkey, &prik, &pubk); if (kmfrv != KMF_OK) return (kmfrv); SET_VALUE(kmf_set_csr_pubkey(kmfhandle, &pubk, &csr), "SetCSRPubKey"); SET_VALUE(kmf_set_csr_version(&csr, 2), "SetCSRVersion"); SET_VALUE(kmf_set_csr_subject(&csr, &csrSubject), "kmf_set_csr_subject"); SET_VALUE(kmf_set_csr_sig_alg(&csr, sigAlg), "kmf_set_csr_sig_alg"); if (altname != NULL) { SET_VALUE(kmf_set_csr_subject_altname(&csr, altname, altcrit, alttype), "kmf_set_csr_subject_altname"); } if (kubits != NULL) { SET_VALUE(kmf_set_csr_ku(&csr, kucrit, kubits), "kmf_set_csr_ku"); } if (ekulist != NULL) { int i; for (i = 0; kmfrv == KMF_OK && i < ekulist->eku_count; i++) { SET_VALUE(kmf_add_csr_eku(&csr, &ekulist->ekulist[i], ekulist->critlist[i]), "Extended Key Usage"); } } if ((kmfrv = kmf_sign_csr(kmfhandle, &csr, &prik, &signedCsr)) == KMF_OK) { kmfrv = kmf_create_csr_file(&signedCsr, fmt, fullcsrpath); } cleanup: if (fullkeypath) free(fullkeypath); if (fullcsrpath) free(fullcsrpath); kmf_free_data(&signedCsr); kmf_free_kmf_key(kmfhandle, &prik); kmf_free_signed_csr(&csr); return (kmfrv); }
int pk_gencsr(int argc, char *argv[]) { KMF_RETURN rv; int opt; extern int optind_av; extern char *optarg_av; KMF_KEYSTORE_TYPE kstype = 0; char *subject = NULL; char *tokenname = NULL; char *dir = NULL; char *prefix = NULL; int keylen = PK_DEFAULT_KEYLENGTH; char *certlabel = NULL; char *outcsr = NULL; char *outkey = NULL; char *format = NULL; char *altname = NULL; char *kustr = NULL; char *ekustr = NULL; char *hashname = NULL; uint16_t kubits = 0; char *keytype = PK_DEFAULT_KEYTYPE; KMF_HANDLE_T kmfhandle = NULL; KMF_ENCODE_FORMAT fmt = KMF_FORMAT_ASN1; KMF_KEY_ALG keyAlg = KMF_RSA; KMF_ALGORITHM_INDEX sigAlg = KMF_ALGID_SHA1WithRSA; boolean_t interactive = B_FALSE; char *subname = NULL; KMF_CREDENTIAL tokencred = {NULL, 0}; KMF_GENERALNAMECHOICES alttype = 0; int altcrit = 0, kucrit = 0; EKU_LIST *ekulist = NULL; KMF_OID *curveoid = NULL; /* ECC */ KMF_OID *hashoid = NULL; int y_flag = 0; while ((opt = getopt_av(argc, argv, "ik:(keystore)s:(subject)n:(nickname)A:(altname)" "u:(keyusage)T:(token)d:(dir)p:(prefix)t:(keytype)" "y:(keylen)l:(label)c:(outcsr)e:(eku)C:(curve)" "K:(outkey)F:(format)E(listcurves)h:(hash)")) != EOF) { switch (opt) { case 'A': altname = optarg_av; break; case 'i': if (interactive) return (PK_ERR_USAGE); else if (subject) { cryptoerror(LOG_STDERR, gettext("Interactive (-i) and " "subject options are mutually " "exclusive.\n")); return (PK_ERR_USAGE); } else interactive = B_TRUE; break; case 'k': kstype = KS2Int(optarg_av); if (kstype == 0) return (PK_ERR_USAGE); break; case 's': if (subject) return (PK_ERR_USAGE); else if (interactive) { cryptoerror(LOG_STDERR, gettext("Interactive (-i) and " "subject options are mutually " "exclusive.\n")); return (PK_ERR_USAGE); } else subject = optarg_av; break; case 'l': case 'n': if (certlabel) return (PK_ERR_USAGE); certlabel = optarg_av; break; case 'T': if (tokenname) return (PK_ERR_USAGE); tokenname = optarg_av; break; case 'd': dir = optarg_av; break; case 'p': if (prefix) return (PK_ERR_USAGE); prefix = optarg_av; break; case 't': keytype = optarg_av; break; case 'u': kustr = optarg_av; break; case 'y': if (sscanf(optarg_av, "%d", &keylen) != 1) { cryptoerror(LOG_STDERR, gettext("Unrecognized " "key length (%s)\n"), optarg_av); return (PK_ERR_USAGE); } y_flag++; break; case 'c': if (outcsr) return (PK_ERR_USAGE); outcsr = optarg_av; break; case 'K': if (outkey) return (PK_ERR_USAGE); outkey = optarg_av; break; case 'F': if (format) return (PK_ERR_USAGE); format = optarg_av; break; case 'e': ekustr = optarg_av; break; case 'C': curveoid = ecc_name_to_oid(optarg_av); if (curveoid == NULL) { cryptoerror(LOG_STDERR, gettext("Unrecognized ECC " "curve.\n")); return (PK_ERR_USAGE); } break; case 'E': /* * This argument is only to be used * by itself, no other options should * be present. */ if (argc != 2) { cryptoerror(LOG_STDERR, gettext("listcurves has no other " "options.\n")); return (PK_ERR_USAGE); } show_ecc_curves(); return (0); case 'h': hashname = optarg_av; hashoid = ecc_name_to_oid(optarg_av); if (hashoid == NULL) { cryptoerror(LOG_STDERR, gettext("Unrecognized hash.\n")); return (PK_ERR_USAGE); } break; default: cryptoerror(LOG_STDERR, gettext( "unrecognized gencsr option '%s'\n"), argv[optind_av]); return (PK_ERR_USAGE); } } /* No additional args allowed. */ argc -= optind_av; argv += optind_av; if (argc) { return (PK_ERR_USAGE); } /* Assume keystore = PKCS#11 if not specified. */ if (kstype == 0) kstype = KMF_KEYSTORE_PK11TOKEN; DIR_OPTION_CHECK(kstype, dir); if (EMPTYSTRING(outcsr) && interactive) { (void) get_filename("CSR", &outcsr); } if (EMPTYSTRING(outcsr)) { (void) printf(gettext("A filename must be specified to hold" "the final certificate request data.\n")); return (PK_ERR_USAGE); } /* * verify that the outcsr file does not already exist * and that it can be created. */ rv = verify_file(outcsr); if (rv == KMF_ERR_OPEN_FILE) { cryptoerror(LOG_STDERR, gettext("Warning: file \"%s\" exists, " "will be overwritten."), outcsr); if (yesno(gettext("Continue with gencsr? "), gettext("Respond with yes or no.\n"), B_FALSE) == B_FALSE) { return (0); } else { /* remove the file */ (void) unlink(outcsr); } } else if (rv != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Warning: error accessing \"%s\""), outcsr); return (rv); } if ((kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN)) { if (EMPTYSTRING(certlabel) && interactive) (void) get_certlabel(&certlabel); if (EMPTYSTRING(certlabel)) { cryptoerror(LOG_STDERR, gettext("A label must be " "specified to create a certificate request.\n")); return (PK_ERR_USAGE); } } else if (kstype == KMF_KEYSTORE_OPENSSL) { if (EMPTYSTRING(outkey) && interactive) (void) get_filename("private key", &outkey); if (EMPTYSTRING(outkey)) { cryptoerror(LOG_STDERR, gettext("A key filename " "must be specified to create a certificate " "request.\n")); return (PK_ERR_USAGE); } } if (format && (fmt = Str2Format(format)) == KMF_FORMAT_UNDEF) { cryptoerror(LOG_STDERR, gettext("Error parsing format string (%s).\n"), format); return (PK_ERR_USAGE); } if (format && fmt != KMF_FORMAT_ASN1 && fmt != KMF_FORMAT_PEM) { cryptoerror(LOG_STDERR, gettext("CSR must be DER or PEM format.\n")); return (PK_ERR_USAGE); } /* * Check the subject name. * If interactive is true, get it now interactively. */ if (interactive) { if (get_subname(&subname) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Failed to get the " "subject name interactively.\n")); return (PK_ERR_USAGE); } } else { if (EMPTYSTRING(subject)) { cryptoerror(LOG_STDERR, gettext("A subject name or " "-i must be specified to create a certificate " "request.\n")); return (PK_ERR_USAGE); } else { subname = strdup(subject); if (subname == NULL) { cryptoerror(LOG_STDERR, gettext("Out of memory.\n")); return (PK_ERR_SYSTEM); } } } if (altname != NULL) { rv = verify_altname(altname, &alttype, &altcrit); if (rv != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Subject AltName " "must be specified as a name=value pair. " "See the man page for details.")); goto end; } else { /* advance the altname past the '=' sign */ char *p = strchr(altname, '='); if (p != NULL) altname = p + 1; } } if (kustr != NULL) { rv = verify_keyusage(kustr, &kubits, &kucrit); if (rv != KMF_OK) { cryptoerror(LOG_STDERR, gettext("KeyUsage " "must be specified as a comma-separated list. " "See the man page for details.")); goto end; } } if (ekustr != NULL) { rv = verify_ekunames(ekustr, &ekulist); if (rv != KMF_OK) { (void) fprintf(stderr, gettext("EKUs must " "be specified as a comma-separated list. " "See the man page for details.\n")); rv = PK_ERR_USAGE; goto end; } } if ((rv = Str2KeyType(keytype, hashoid, &keyAlg, &sigAlg)) != 0) { cryptoerror(LOG_STDERR, gettext("Unsupported key/hash combination (%s/%s).\n"), keytype, (hashname ? hashname : "none")); goto end; } if (curveoid != NULL && keyAlg != KMF_ECDSA) { cryptoerror(LOG_STDERR, gettext("EC curves are only " "valid for EC keytypes.\n")); return (PK_ERR_USAGE); } if (keyAlg == KMF_ECDSA && curveoid == NULL) { cryptoerror(LOG_STDERR, gettext("A curve must be " "specifed when using EC keys.\n")); return (PK_ERR_USAGE); } if (keyAlg == KMF_ECDSA && kstype == KMF_KEYSTORE_OPENSSL) { (void) fprintf(stderr, gettext("ECC certificates are" "only supported with the pkcs11 and nss keystores\n")); rv = PK_ERR_USAGE; goto end; } /* Adjust default keylength for NSS and DSA */ if (keyAlg == KMF_DSA && !y_flag && kstype == KMF_KEYSTORE_NSS) keylen = 1024; if (kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN) { if (tokenname == NULL || !strlen(tokenname)) { if (kstype == KMF_KEYSTORE_NSS) { tokenname = "internal"; } else { tokenname = PK_DEFAULT_PK11TOKEN; } } (void) get_token_password(kstype, tokenname, &tokencred); } if ((rv = kmf_initialize(&kmfhandle, NULL, NULL)) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Error initializing KMF\n")); return (PK_ERR_USAGE); } if (kstype == KMF_KEYSTORE_NSS) { if (dir == NULL) dir = PK_DEFAULT_DIRECTORY; rv = gencsr_nss(kmfhandle, tokenname, subname, altname, alttype, altcrit, certlabel, dir, prefix, keyAlg, keylen, kubits, kucrit, fmt, outcsr, &tokencred, ekulist, sigAlg, curveoid); } else if (kstype == KMF_KEYSTORE_PK11TOKEN) { rv = gencsr_pkcs11(kmfhandle, tokenname, subname, altname, alttype, altcrit, certlabel, keyAlg, keylen, kubits, kucrit, fmt, outcsr, &tokencred, ekulist, sigAlg, curveoid); } else if (kstype == KMF_KEYSTORE_OPENSSL) { rv = gencsr_file(kmfhandle, keyAlg, keylen, fmt, subname, altname, alttype, altcrit, kubits, kucrit, outcsr, outkey, ekulist, sigAlg); } end: if (rv != KMF_OK) { display_error(kmfhandle, rv, gettext("Error creating CSR or keypair")); if (rv == KMF_ERR_RDN_PARSER) { cryptoerror(LOG_STDERR, gettext("subject or " "issuer name must be in proper DN format.\n")); } } if (ekulist != NULL) free_eku_list(ekulist); if (subname) free(subname); if (tokencred.cred != NULL) free(tokencred.cred); (void) kmf_finalize(kmfhandle); if (rv != KMF_OK) return (PK_ERR_USAGE); return (0); }
/* * Retrieve multiple files from the command line, transferring * files of the form "host:path", "ftp://host/path" using the * ftp protocol, and files of the form "http://host/path" using * the http protocol. * If path has a trailing "/", then return (-1); * the path will be cd-ed into and the connection remains open, * and the function will return -1 (to indicate the connection * is alive). * If an error occurs the return value will be the offset+1 in * argv[] of the file that caused a problem (i.e, argv[x] * returns x+1) * Otherwise, 0 is returned if all files retrieved successfully. */ int auto_fetch(int argc, char *argv[], char *outfile) { char *xargv[5]; char *cp, *url, *host, *dir, *file, *portnum; char *username, *pass, *pathstart; char *ftpproxy, *httpproxy; int rval, xargc; volatile int argpos; int dirhasglob, filehasglob, oautologin; char rempath[MAXPATHLEN]; argpos = 0; if (setjmp(toplevel)) { if (connected) disconnect(0, NULL); return (argpos + 1); } (void)signal(SIGINT, (sig_t)intr); (void)signal(SIGPIPE, (sig_t)lostpeer); if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0') ftpproxy = NULL; if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0') httpproxy = NULL; /* * Loop through as long as there's files to fetch. */ for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) { if (strchr(argv[argpos], ':') == NULL) break; host = dir = file = portnum = username = pass = NULL; /* * We muck with the string, so we make a copy. */ url = strdup(argv[argpos]); if (url == NULL) errx(1, "Can't allocate memory for auto-fetch."); /* * Try HTTP URL-style arguments first. */ if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || #ifndef SMALL /* even if we compiled without SSL, url_get will check */ strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 || #endif /* !SMALL */ strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) { redirect_loop = 0; if (url_get(url, httpproxy, outfile) == -1) rval = argpos + 1; continue; } /* * Try FTP URL-style arguments next. If ftpproxy is * set, use url_get() instead of standard ftp. * Finally, try host:file. */ host = url; if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) { char *passend, *passagain, *userend; if (ftpproxy) { if (url_get(url, ftpproxy, outfile) == -1) rval = argpos + 1; continue; } host += sizeof(FTP_URL) - 1; dir = strchr(host, '/'); /* Look for [user:pass@]host[:port] */ /* check if we have "user:pass@" */ userend = strchr(host, ':'); passend = strchr(host, '@'); if (passend && userend && userend < passend && (!dir || passend < dir)) { username = host; pass = userend + 1; host = passend + 1; *userend = *passend = '\0'; passagain = strchr(host, '@'); if (strchr(pass, '@') != NULL || (passagain != NULL && passagain < dir)) { warnx(at_encoding_warning); goto bad_ftp_url; } if (EMPTYSTRING(username)) { bad_ftp_url: warnx("Invalid URL: %s", argv[argpos]); rval = argpos + 1; continue; } username = urldecode(username); pass = urldecode(pass); } #ifdef INET6 /* check [host]:port, or [host] */ if (host[0] == '[') { cp = strchr(host, ']'); if (cp && (!dir || cp < dir)) { if (cp + 1 == dir || cp[1] == ':') { host++; *cp++ = '\0'; } else cp = NULL; } else cp = host; } else cp = host; #else cp = host; #endif /* split off host[:port] if there is */ if (cp) { portnum = strchr(cp, ':'); pathstart = strchr(cp, '/'); /* : in path is not a port # indicator */ if (portnum && pathstart && pathstart < portnum) portnum = NULL; if (!portnum) ; else { if (!dir) ; else if (portnum + 1 < dir) { *portnum++ = '\0'; /* * XXX should check if portnum * is decimal number */ } else { /* empty portnum */ goto bad_ftp_url; } } } else portnum = NULL; } else { /* classic style `host:file' */ dir = strchr(host, ':'); } if (EMPTYSTRING(host)) { rval = argpos + 1; continue; } /* * If dir is NULL, the file wasn't specified * (URL looked something like ftp://host) */ if (dir != NULL) *dir++ = '\0'; /* * Extract the file and (if present) directory name. */ if (!EMPTYSTRING(dir)) { cp = strrchr(dir, '/'); if (cp != NULL) { *cp++ = '\0'; file = cp; } else { file = dir; dir = NULL; } } #ifndef SMALL if (debug) fprintf(ttyout, "user %s:%s host %s port %s dir %s file %s\n", username, pass ? "XXXX" : NULL, host, portnum, dir, file); #endif /* !SMALL */ /* * Set up the connection. */ if (connected) disconnect(0, NULL); xargv[0] = __progname; xargv[1] = host; xargv[2] = NULL; xargc = 2; if (!EMPTYSTRING(portnum)) { xargv[2] = portnum; xargv[3] = NULL; xargc = 3; } oautologin = autologin; if (username != NULL) autologin = 0; setpeer(xargc, xargv); autologin = oautologin; if ((connected == 0) || ((connected == 1) && !ftp_login(host, username, pass))) { warnx("Can't connect or login to host `%s'", host); rval = argpos + 1; continue; } /* Always use binary transfers. */ setbinary(0, NULL); dirhasglob = filehasglob = 0; if (doglob) { if (!EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL) dirhasglob = 1; if (!EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL) filehasglob = 1; } /* Change directories, if necessary. */ if (!EMPTYSTRING(dir) && !dirhasglob) { xargv[0] = "cd"; xargv[1] = dir; xargv[2] = NULL; cd(2, xargv); if (!dirchange) { rval = argpos + 1; continue; } } if (EMPTYSTRING(file)) { rval = -1; continue; } if (verbose) fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file); if (dirhasglob) { snprintf(rempath, sizeof(rempath), "%s/%s", dir, file); file = rempath; } /* Fetch the file(s). */ xargc = 2; xargv[0] = "get"; xargv[1] = file; xargv[2] = NULL; if (dirhasglob || filehasglob) { int ointeractive; ointeractive = interactive; interactive = 0; xargv[0] = "mget"; #ifndef SMALL if (resume) { xargc = 3; xargv[1] = "-c"; xargv[2] = file; xargv[3] = NULL; } #endif /* !SMALL */ mget(xargc, xargv); interactive = ointeractive; } else { if (outfile != NULL) { xargv[2] = outfile; xargv[3] = NULL; xargc++; } #ifndef SMALL if (resume) reget(xargc, xargv); else #endif /* !SMALL */ get(xargc, xargv); } if ((code / 100) != COMPLETE) rval = argpos + 1; } if (connected && rval != -1) disconnect(0, NULL); return (rval); }
int main(int volatile argc, char **volatile argv) { int ch, rval; struct passwd *pw; char *cp, *ep, *anonuser, *anonpass, *upload_path, *src_addr; int dumbterm, s, isupload; size_t len; socklen_t slen; tzset(); #if 0 /* tnftp */ /* XXX */ setlocale(LC_ALL, ""); #endif /* tnftp */ setprogname(argv[0]); sigint_raised = 0; ftpport = "ftp"; httpport = "http"; gateport = NULL; cp = getenv("FTPSERVERPORT"); if (cp != NULL) gateport = cp; else gateport = "ftpgate"; doglob = 1; interactive = 1; autologin = 1; passivemode = 1; activefallback = 1; preserve = 1; verbose = 0; progress = 0; gatemode = 0; data = -1; outfile = NULL; restartautofetch = 0; #ifndef NO_EDITCOMPLETE editing = 0; el = NULL; hist = NULL; #endif bytes = 0; mark = HASHBYTES; rate_get = 0; rate_get_incr = DEFAULTINCR; rate_put = 0; rate_put_incr = DEFAULTINCR; #ifdef INET6 epsv4 = 1; #else epsv4 = 0; #endif epsv4bad = 0; src_addr = NULL; upload_path = NULL; isupload = 0; reply_callback = NULL; family = AF_UNSPEC; netrc[0] = '\0'; cp = getenv("NETRC"); if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc)) errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG)); /* * Get the default socket buffer sizes if we don't already have them. * It doesn't matter which socket we do this to, because on the first * call no socket buffer sizes will have been modified, so we are * guaranteed to get the system defaults. */ s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) err(1, "Can't create socket to determine default socket sizes"); slen = sizeof(rcvbuf_size); if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf_size, &slen) == -1) err(1, "Unable to get default rcvbuf size"); slen = sizeof(sndbuf_size); if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf_size, &slen) == -1) err(1, "Unable to get default sndbuf size"); (void)close(s); /* sanity check returned buffer sizes */ if (rcvbuf_size <= 0) rcvbuf_size = 8 * 1024; if (sndbuf_size <= 0) sndbuf_size = 8 * 1024; if (sndbuf_size > 8 * 1024 * 1024) sndbuf_size = 8 * 1024 * 1024; if (rcvbuf_size > 8 * 1024 * 1024) rcvbuf_size = 8 * 1024 * 1024; marg_sl = ftp_sl_init(); if ((tmpdir = getenv("TMPDIR")) == NULL) tmpdir = _PATH_TMP; /* Set default operation mode based on FTPMODE environment variable */ if ((cp = getenv("FTPMODE")) != NULL) { if (strcasecmp(cp, "passive") == 0) { passivemode = 1; activefallback = 0; } else if (strcasecmp(cp, "active") == 0) { passivemode = 0; activefallback = 0; } else if (strcasecmp(cp, "gate") == 0) { gatemode = 1; } else if (strcasecmp(cp, "auto") == 0) { passivemode = 1; activefallback = 1; } else warnx("Unknown $FTPMODE `%s'; using defaults", cp); } if (strcmp(getprogname(), "pftp") == 0) { passivemode = 1; activefallback = 0; } else if (strcmp(getprogname(), "gate-ftp") == 0) gatemode = 1; gateserver = getenv("FTPSERVER"); if (gateserver == NULL || *gateserver == '\0') gateserver = GATE_SERVER; if (gatemode) { if (*gateserver == '\0') { warnx( "Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp"); gatemode = 0; } } cp = getenv("TERM"); if (cp == NULL || strcmp(cp, "dumb") == 0) dumbterm = 1; else dumbterm = 0; fromatty = isatty(fileno(stdin)); ttyout = stdout; if (isatty(fileno(ttyout))) { verbose = 1; /* verbose if to a tty */ if (! dumbterm) { #ifndef NO_EDITCOMPLETE if (fromatty) /* editing mode on if tty is usable */ editing = 1; #endif #ifndef NO_PROGRESS if (foregroundproc()) progress = 1; /* progress bar on if fg */ #endif } } while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) { switch (ch) { case '4': family = AF_INET; break; case '6': #ifdef INET6 family = AF_INET6; #else warnx("INET6 support is not available; ignoring -6"); #endif break; case 'A': activefallback = 0; passivemode = 0; break; case 'a': anonftp = 1; break; case 'd': options |= SO_DEBUG; ftp_debug++; break; case 'e': #ifndef NO_EDITCOMPLETE editing = 0; #endif break; case 'f': flushcache = 1; break; case 'g': doglob = 0; break; case 'i': interactive = 0; break; case 'n': autologin = 0; break; case 'N': if (strlcpy(netrc, optarg, sizeof(netrc)) >= sizeof(netrc)) errx(1, "%s: %s", optarg, strerror(ENAMETOOLONG)); break; case 'o': outfile = optarg; if (strcmp(outfile, "-") == 0) ttyout = stderr; break; case 'p': passivemode = 1; activefallback = 0; break; case 'P': ftpport = optarg; break; case 'q': quit_time = strtol(optarg, &ep, 10); if (quit_time < 1 || *ep != '\0') errx(1, "Bad quit value: %s", optarg); break; case 'r': retry_connect = strtol(optarg, &ep, 10); if (retry_connect < 1 || *ep != '\0') errx(1, "Bad retry value: %s", optarg); break; case 'R': restartautofetch = 1; break; case 's': src_addr = optarg; break; case 't': trace = 1; break; case 'T': { int targc; char *targv[6], *oac; /* look for `dir,max[,incr]' */ targc = 0; targv[targc++] = "-T"; oac = ftp_strdup(optarg); while ((cp = strsep(&oac, ",")) != NULL) { if (*cp == '\0') { warnx("Bad throttle value `%s'", optarg); usage(); /* NOTREACHED */ } targv[targc++] = cp; if (targc >= 5) break; } if (parserate(targc, targv, 1) == -1) usage(); free(oac); break; } case 'u': { isupload = 1; interactive = 0; upload_path = ftp_strdup(optarg); break; } case 'v': progress = verbose = 1; break; case 'V': progress = verbose = 0; break; default: usage(); } } /* set line buffering on ttyout */ setvbuf(ttyout, NULL, _IOLBF, 0); argc -= optind; argv += optind; cpend = 0; /* no pending replies */ proxy = 0; /* proxy not active */ crflag = 1; /* strip c.r. on ascii gets */ sendport = -1; /* not using ports */ if (src_addr != NULL) { struct addrinfo hints; int error; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; error = getaddrinfo(src_addr, NULL, &hints, &bindai); if (error) { errx(1, "Can't lookup `%s': %s", src_addr, (error == EAI_SYSTEM) ? strerror(errno) : gai_strerror(error)); } } /* * Cache the user name and home directory. */ localhome = NULL; localname = NULL; anonuser = "******"; cp = getenv("HOME"); if (! EMPTYSTRING(cp)) localhome = ftp_strdup(cp); pw = NULL; cp = getlogin(); if (cp != NULL) pw = getpwnam(cp); if (pw == NULL) pw = getpwuid(getuid()); if (pw != NULL) { if (localhome == NULL && !EMPTYSTRING(pw->pw_dir)) localhome = ftp_strdup(pw->pw_dir); localname = ftp_strdup(pw->pw_name); anonuser = localname; } if (netrc[0] == '\0' && localhome != NULL) { if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) || strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) { warnx("%s/.netrc: %s", localhome, strerror(ENAMETOOLONG)); netrc[0] = '\0'; } } if (localhome == NULL) localhome = ftp_strdup("/"); /* * Every anonymous FTP server I've encountered will accept the * string "username@", and will append the hostname itself. We * do this by default since many servers are picky about not * having a FQDN in the anonymous password. * - [email protected] */ len = strlen(anonuser) + 2; anonpass = ftp_malloc(len); (void)strlcpy(anonpass, anonuser, len); (void)strlcat(anonpass, "@", len); /* * set all the defaults for options defined in * struct option optiontab[] declared in cmdtab.c */ setupoption("anonpass", getenv("FTPANONPASS"), anonpass); setupoption("ftp_proxy", getenv(FTP_PROXY), ""); setupoption("http_proxy", getenv(HTTP_PROXY), ""); setupoption("no_proxy", getenv(NO_PROXY), ""); setupoption("pager", getenv("PAGER"), DEFAULTPAGER); setupoption("prompt", getenv("FTPPROMPT"), DEFAULTPROMPT); setupoption("rprompt", getenv("FTPRPROMPT"), DEFAULTRPROMPT); free(anonpass); setttywidth(0); #ifdef SIGINFO (void)xsignal(SIGINFO, psummary); #endif (void)xsignal(SIGQUIT, psummary); (void)xsignal(SIGUSR1, crankrate); (void)xsignal(SIGUSR2, crankrate); (void)xsignal(SIGWINCH, setttywidth); if (argc > 0) { if (isupload) { rval = auto_put(argc, argv, upload_path); sigint_or_rval_exit: if (sigint_raised) { (void)xsignal(SIGINT, SIG_DFL); raise(SIGINT); } exit(rval); } else if (strchr(argv[0], ':') != NULL && ! isipv6addr(argv[0])) { rval = auto_fetch(argc, argv); if (rval >= 0) /* -1 == connected and cd-ed */ goto sigint_or_rval_exit; } else { char *xargv[4], *user, *host; if ((rval = sigsetjmp(toplevel, 1))) goto sigint_or_rval_exit; (void)xsignal(SIGINT, intr); (void)xsignal(SIGPIPE, lostpeer); user = NULL; host = argv[0]; cp = strchr(host, '@'); if (cp) { *cp = '\0'; user = host; host = cp + 1; } /* XXX discards const */ xargv[0] = (char *)getprogname(); xargv[1] = host; xargv[2] = argv[1]; xargv[3] = NULL; do { int oautologin; oautologin = autologin; if (user != NULL) { anonftp = 0; autologin = 0; } setpeer(argc+1, xargv); autologin = oautologin; if (connected == 1 && user != NULL) (void)ftp_login(host, user, NULL); if (!retry_connect) break; if (!connected) { macnum = 0; fprintf(ttyout, "Retrying in %d seconds...\n", retry_connect); sleep(retry_connect); } } while (!connected); retry_connect = 0; /* connected, stop hiding msgs */ } } if (isupload) usage(); #ifndef NO_EDITCOMPLETE controlediting(); #endif /* !NO_EDITCOMPLETE */ (void)sigsetjmp(toplevel, 1); (void)xsignal(SIGINT, intr); (void)xsignal(SIGPIPE, lostpeer); for (;;) cmdscanner(); }
/* * Retrieve URL, via the proxy in $proxyvar if necessary. * Modifies the string argument given. * Returns -1 on failure, 0 on success */ static int url_get(const char *origline, const char *proxyenv, const char *outfile) { char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4]; char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL; int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1; struct addrinfo hints, *res0, *res; const char * volatile savefile; char * volatile proxyurl = NULL; char *cookie = NULL; volatile int s = -1, out; volatile sig_t oldintr; FILE *fin = NULL; off_t hashbytes; const char *errstr; size_t len, wlen; #ifndef SMALL char *sslpath = NULL, *sslhost = NULL; int ishttpsurl = 0; SSL_CTX *ssl_ctx = NULL; #endif /* !SMALL */ SSL *ssl = NULL; int status; newline = strdup(origline); if (newline == NULL) errx(1, "Can't allocate memory to parse URL"); if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) host = newline + sizeof(HTTP_URL) - 1; else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) { host = newline + sizeof(FTP_URL) - 1; isftpurl = 1; } else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) { host = newline + sizeof(FILE_URL) - 1; isfileurl = 1; #ifndef SMALL } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) { host = newline + sizeof(HTTPS_URL) - 1; ishttpsurl = 1; #endif /* !SMALL */ } else errx(1, "url_get: Invalid URL '%s'", newline); if (isfileurl) { path = host; } else { path = strchr(host, '/'); /* find path */ if (EMPTYSTRING(path)) { if (isftpurl) goto noftpautologin; warnx("Invalid URL (no `/' after host): %s", origline); goto cleanup_url_get; } *path++ = '\0'; if (EMPTYSTRING(path)) { if (isftpurl) goto noftpautologin; warnx("Invalid URL (no file after host): %s", origline); goto cleanup_url_get; } } if (outfile) savefile = outfile; else savefile = basename(path); #ifndef SMALL if (resume && (strcmp(savefile, "-") == 0)) { warnx("can't append to stdout"); goto cleanup_url_get; } #endif /* !SMALL */ if (EMPTYSTRING(savefile)) { if (isftpurl) goto noftpautologin; warnx("Invalid URL (no file after directory): %s", origline); goto cleanup_url_get; } if (!isfileurl && proxyenv != NULL) { /* use proxy */ #ifndef SMALL if (ishttpsurl) { sslpath = strdup(path); sslhost = strdup(host); if (! sslpath || ! sslhost) errx(1, "Can't allocate memory for https path/host."); } #endif /* !SMALL */ proxyurl = strdup(proxyenv); if (proxyurl == NULL) errx(1, "Can't allocate memory for proxy URL."); if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) host = proxyurl + sizeof(HTTP_URL) - 1; else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0) host = proxyurl + sizeof(FTP_URL) - 1; else { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } if (EMPTYSTRING(host)) { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } *--path = '/'; /* add / back to real path */ path = strchr(host, '/'); /* remove trailing / on host */ if (!EMPTYSTRING(path)) *path++ = '\0'; /* i guess this ++ is useless */ path = strchr(host, '@'); /* look for credentials in proxy */ if (!EMPTYSTRING(path)) { *path++ = '\0'; cookie = strchr(host, ':'); if (EMPTYSTRING(cookie)) { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } cookie = malloc(COOKIE_MAX_LEN); b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN); /* * This removes the password from proxyenv, * filling with stars */ for (host = strchr(proxyenv + 5, ':'); *host != '@'; host++) *host = '*'; host = path; } path = newline; } if (isfileurl) { struct stat st; s = open(path, O_RDONLY); if (s == -1) { warn("Can't open file %s", path); goto cleanup_url_get; } if (fstat(s, &st) == -1) filesize = -1; else filesize = st.st_size; /* Open the output file. */ if (strcmp(savefile, "-") != 0) { #ifndef SMALL if (resume) out = open(savefile, O_APPEND | O_WRONLY); else #endif /* !SMALL */ out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); if (out < 0) { warn("Can't open %s", savefile); goto cleanup_url_get; } } else out = fileno(stdout); #ifndef SMALL if (resume) { if (fstat(out, &st) == -1) { warn("Can't fstat %s", savefile); goto cleanup_url_get; } if (lseek(s, st.st_size, SEEK_SET) == -1) { warn("Can't lseek %s", path); goto cleanup_url_get; } restart_point = st.st_size; } #endif /* !SMALL */ /* Trap signals */ oldintr = NULL; if (setjmp(httpabort)) { if (oldintr) (void)signal(SIGINT, oldintr); goto cleanup_url_get; } oldintr = signal(SIGINT, abortfile); bytes = 0; hashbytes = mark; progressmeter(-1); if ((buf = malloc(4096)) == NULL) errx(1, "Can't allocate memory for transfer buffer"); /* Finally, suck down the file. */ i = 0; while ((len = read(s, buf, 4096)) > 0) { bytes += len; for (cp = buf; len > 0; len -= i, cp += i) { if ((i = write(out, cp, len)) == -1) { warn("Writing %s", savefile); goto cleanup_url_get; } else if (i == 0) break; } if (hash && !progress) { while (bytes >= hashbytes) { (void)putc('#', ttyout); hashbytes += mark; } (void)fflush(ttyout); } } if (hash && !progress && bytes > 0) { if (bytes < mark) (void)putc('#', ttyout); (void)putc('\n', ttyout); (void)fflush(ttyout); } if (len != 0) { warn("Reading from file"); goto cleanup_url_get; } progressmeter(1); if (verbose) fputs("Successfully retrieved file.\n", ttyout); (void)signal(SIGINT, oldintr); rval = 0; goto cleanup_url_get; } if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL && (hosttail[1] == '\0' || hosttail[1] == ':')) { host++; *hosttail++ = '\0'; } else hosttail = host; portnum = strrchr(hosttail, ':'); /* find portnum */ if (portnum != NULL) *portnum++ = '\0'; #ifndef SMALL if (debug) fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n", host, portnum, path, savefile); #endif /* !SMALL */ memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; #ifndef SMALL port = portnum ? portnum : (ishttpsurl ? httpsport : httpport); #else /* !SMALL */ port = portnum ? portnum : httpport; #endif /* !SMALL */ error = getaddrinfo(host, port, &hints, &res0); /* * If the services file is corrupt/missing, fall back * on our hard-coded defines. */ if (error == EAI_SERVICE && port == httpport) { snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT); error = getaddrinfo(host, pbuf, &hints, &res0); #ifndef SMALL } else if (error == EAI_SERVICE && port == httpsport) { snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT); error = getaddrinfo(host, pbuf, &hints, &res0); #endif /* !SMALL */ } if (error) { warnx("%s: %s", gai_strerror(error), host); goto cleanup_url_get; } s = -1; for (res = res0; res; res = res->ai_next) { if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) strlcpy(hbuf, "(unknown)", sizeof(hbuf)); if (verbose) fprintf(ttyout, "Trying %s...\n", hbuf); s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (s == -1) { cause = "socket"; continue; } again: if (connect(s, res->ai_addr, res->ai_addrlen) < 0) { int save_errno; if (errno == EINTR) goto again; save_errno = errno; close(s); errno = save_errno; s = -1; cause = "connect"; continue; } /* get port in numeric */ if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0, pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0) port = pbuf; else port = NULL; #ifndef SMALL if (proxyenv && sslhost) proxy_connect(s, sslhost); #endif /* !SMALL */ break; } freeaddrinfo(res0); if (s < 0) { warn("%s", cause); goto cleanup_url_get; } #ifndef SMALL if (ishttpsurl) { if (proxyenv && sslpath) { ishttpsurl = 0; proxyurl = NULL; path = sslpath; } SSL_library_init(); SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); ssl_ctx = SSL_CTX_new(SSLv23_client_method()); ssl = SSL_new(ssl_ctx); if (ssl == NULL || ssl_ctx == NULL) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } if (SSL_set_fd(ssl, s) == 0) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } if (SSL_connect(ssl) <= 0) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } } else { fin = fdopen(s, "r+"); } #else /* !SMALL */ fin = fdopen(s, "r+"); #endif /* !SMALL */ if (verbose) fprintf(ttyout, "Requesting %s", origline); /* * Construct and send the request. Proxy requests don't want leading /. */ #ifndef SMALL cookie_get(host, path, ishttpsurl, &buf); #endif /* !SMALL */ if (proxyurl) { if (verbose) fprintf(ttyout, " (via %s)\n", proxyenv); /* * Host: directive must use the destination host address for * the original URI (path). We do not attach it at this moment. */ if (cookie) ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n" "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n", path, cookie, buf ? buf : "", HTTP_USER_AGENT); else ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n", path, buf ? buf : "", HTTP_USER_AGENT); } else { ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", path, #ifndef SMALL resume ? "HTTP/1.1" : #endif /* !SMALL */ "HTTP/1.0"); if (strchr(host, ':')) { char *h, *p; /* * strip off scoped address portion, since it's * local to node */ h = strdup(host); if (h == NULL) errx(1, "Can't allocate memory."); if ((p = strchr(h, '%')) != NULL) *p = '\0'; ftp_printf(fin, ssl, "[%s]", h); free(h); } else ftp_printf(fin, ssl, "%s", host); /* * Send port number only if it's specified and does not equal * 80. Some broken HTTP servers get confused if you explicitly * send them the port number. */ #ifndef SMALL if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0) ftp_printf(fin, ssl, ":%s", port); if (resume) { int ret; struct stat stbuf; ret = stat(savefile, &stbuf); if (ret < 0) { if (verbose) fprintf(ttyout, "\n"); warn("Can't open %s", savefile); goto cleanup_url_get; } restart_point = stbuf.st_size; ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-", (long long)restart_point); } #else /* !SMALL */ if (port && strcmp(port, "80") != 0) ftp_printf(fin, ssl, ":%s", port); #endif /* !SMALL */ ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n", buf ? buf : "", HTTP_USER_AGENT); if (verbose) fprintf(ttyout, "\n"); } #ifndef SMALL free(buf); #endif /* !SMALL */ buf = NULL; if (fin != NULL && fflush(fin) == EOF) { warn("Writing HTTP request"); goto cleanup_url_get; } if ((buf = ftp_readline(fin, ssl, &len)) == NULL) { warn("Receiving HTTP reply"); goto cleanup_url_get; } while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) buf[--len] = '\0'; #ifndef SMALL if (debug) fprintf(ttyout, "received '%s'\n", buf); #endif /* !SMALL */ cp = strchr(buf, ' '); if (cp == NULL) goto improper; else cp++; strlcpy(ststr, cp, sizeof(ststr)); status = strtonum(ststr, 200, 416, &errstr); if (errstr) { warnx("Error retrieving file: %s", cp); goto cleanup_url_get; } switch (status) { case 200: /* OK */ #ifndef SMALL case 206: /* Partial Content */ break; #endif /* !SMALL */ case 301: /* Moved Permanently */ case 302: /* Found */ case 303: /* See Other */ case 307: /* Temporary Redirect */ isredirect++; if (redirect_loop++ > 10) { warnx("Too many redirections requested"); goto cleanup_url_get; } break; #ifndef SMALL case 416: /* Requested Range Not Satisfiable */ warnx("File is already fully retrieved."); goto cleanup_url_get; #endif /* !SMALL */ default: warnx("Error retrieving file: %s", cp); goto cleanup_url_get; } /* * Read the rest of the header. */ free(buf); filesize = -1; for (;;) { if ((buf = ftp_readline(fin, ssl, &len)) == NULL) { warn("Receiving HTTP reply"); goto cleanup_url_get; } while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) buf[--len] = '\0'; if (len == 0) break; #ifndef SMALL if (debug) fprintf(ttyout, "received '%s'\n", buf); #endif /* !SMALL */ /* Look for some headers */ cp = buf; #define CONTENTLEN "Content-Length: " if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) { cp += sizeof(CONTENTLEN) - 1; filesize = strtonum(cp, 0, LLONG_MAX, &errstr); if (errstr != NULL) goto improper; #ifndef SMALL if (resume) filesize += restart_point; #endif /* !SMALL */ #define LOCATION "Location: " } else if (isredirect && strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) { cp += sizeof(LOCATION) - 1; if (verbose) fprintf(ttyout, "Redirected to %s\n", cp); if (fin != NULL) fclose(fin); else if (s != -1) close(s); free(proxyurl); free(newline); rval = url_get(cp, proxyenv, outfile); free(buf); return (rval); } } /* Open the output file. */ if (strcmp(savefile, "-") != 0) { #ifndef SMALL if (resume) out = open(savefile, O_APPEND | O_WRONLY); else #endif /* !SMALL */ out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); if (out < 0) { warn("Can't open %s", savefile); goto cleanup_url_get; } } else out = fileno(stdout); /* Trap signals */ oldintr = NULL; if (setjmp(httpabort)) { if (oldintr) (void)signal(SIGINT, oldintr); goto cleanup_url_get; } oldintr = signal(SIGINT, aborthttp); bytes = 0; hashbytes = mark; progressmeter(-1); free(buf); /* Finally, suck down the file. */ if ((buf = malloc(4096)) == NULL) errx(1, "Can't allocate memory for transfer buffer"); i = 0; len = 1; while (len > 0) { len = ftp_read(fin, ssl, buf, 4096); bytes += len; for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) { if ((i = write(out, cp, wlen)) == -1) { warn("Writing %s", savefile); goto cleanup_url_get; } else if (i == 0) break; } if (hash && !progress) { while (bytes >= hashbytes) { (void)putc('#', ttyout); hashbytes += mark; } (void)fflush(ttyout); } } if (hash && !progress && bytes > 0) { if (bytes < mark) (void)putc('#', ttyout); (void)putc('\n', ttyout); (void)fflush(ttyout); } if (len != 0) { warn("Reading from socket"); goto cleanup_url_get; } progressmeter(1); if ( #ifndef SMALL !resume && #endif /* !SMALL */ filesize != -1 && len == 0 && bytes != filesize) { if (verbose) fputs("Read short file.\n", ttyout); goto cleanup_url_get; } if (verbose) fputs("Successfully retrieved file.\n", ttyout); (void)signal(SIGINT, oldintr); rval = 0; goto cleanup_url_get; noftpautologin: warnx( "Auto-login using ftp URLs isn't supported when using $ftp_proxy"); goto cleanup_url_get; improper: warnx("Improper response from %s", host); cleanup_url_get: #ifndef SMALL if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); } #endif /* !SMALL */ if (fin != NULL) fclose(fin); else if (s != -1) close(s); free(buf); free(proxyurl); free(newline); return (rval); }
int pk_gencert(int argc, char *argv[]) { int rv; int opt; extern int optind_av; extern char *optarg_av; KMF_KEYSTORE_TYPE kstype = 0; char *subject = NULL; char *tokenname = NULL; char *dir = NULL; char *prefix = NULL; char *keytype = PK_DEFAULT_KEYTYPE; int keylen = PK_DEFAULT_KEYLENGTH; char *trust = NULL; char *lifetime = NULL; char *certlabel = NULL; char *outcert = NULL; char *outkey = NULL; char *format = NULL; char *serstr = NULL; char *altname = NULL; char *keyusagestr = NULL; char *ekustr = NULL; char *hashname = NULL; KMF_GENERALNAMECHOICES alttype = 0; KMF_BIGINT serial = { NULL, 0 }; uint32_t ltime; KMF_HANDLE_T kmfhandle = NULL; KMF_ENCODE_FORMAT fmt = KMF_FORMAT_ASN1; KMF_KEY_ALG keyAlg = KMF_RSA; KMF_ALGORITHM_INDEX sigAlg = KMF_ALGID_SHA1WithRSA; boolean_t interactive = B_FALSE; char *subname = NULL; KMF_CREDENTIAL tokencred = { NULL, 0 }; uint16_t kubits = 0; int altcrit = 0, kucrit = 0; EKU_LIST *ekulist = NULL; KMF_OID *curveoid = NULL; /* ECC */ KMF_OID *hashoid = NULL; int y_flag = 0; while ((opt = getopt_av(argc, argv, "ik:(keystore)s:(subject)n:(nickname)A:(altname)" "T:(token)d:(dir)p:(prefix)t:(keytype)y:(keylen)" "r:(trust)L:(lifetime)l:(label)c:(outcert)e:(eku)" "K:(outkey)S:(serial)F:(format)u:(keyusage)C:(curve)" "E(listcurves)h:(hash)")) != EOF) { if (opt != 'i' && opt != 'E' && EMPTYSTRING(optarg_av)) return (PK_ERR_USAGE); switch (opt) { case 'A': altname = optarg_av; break; case 'i': if (interactive || subject) return (PK_ERR_USAGE); else interactive = B_TRUE; break; case 'k': kstype = KS2Int(optarg_av); if (kstype == 0) return (PK_ERR_USAGE); break; case 's': if (interactive || subject) return (PK_ERR_USAGE); else subject = optarg_av; break; case 'l': case 'n': if (certlabel) return (PK_ERR_USAGE); certlabel = optarg_av; break; case 'T': if (tokenname) return (PK_ERR_USAGE); tokenname = optarg_av; break; case 'd': if (dir) return (PK_ERR_USAGE); dir = optarg_av; break; case 'p': if (prefix) return (PK_ERR_USAGE); prefix = optarg_av; break; case 't': keytype = optarg_av; break; case 'u': keyusagestr = optarg_av; break; case 'y': if (sscanf(optarg_av, "%d", &keylen) != 1) { cryptoerror(LOG_STDERR, gettext("key length must be" "a numeric value (%s)\n"), optarg_av); return (PK_ERR_USAGE); } y_flag++; break; case 'r': if (trust) return (PK_ERR_USAGE); trust = optarg_av; break; case 'L': if (lifetime) return (PK_ERR_USAGE); lifetime = optarg_av; break; case 'c': if (outcert) return (PK_ERR_USAGE); outcert = optarg_av; break; case 'K': if (outkey) return (PK_ERR_USAGE); outkey = optarg_av; break; case 'S': serstr = optarg_av; break; case 'F': if (format) return (PK_ERR_USAGE); format = optarg_av; break; case 'e': ekustr = optarg_av; break; case 'C': curveoid = ecc_name_to_oid(optarg_av); if (curveoid == NULL) { cryptoerror(LOG_STDERR, gettext("Unrecognized ECC " "curve.\n")); return (PK_ERR_USAGE); } break; case 'E': /* * This argument is only to be used * by itself, no other options should * be present. */ if (argc != 2) { cryptoerror(LOG_STDERR, gettext("listcurves has no other " "options.\n")); return (PK_ERR_USAGE); } show_ecc_curves(); return (0); case 'h': hashname = optarg_av; hashoid = ecc_name_to_oid(optarg_av); if (hashoid == NULL) { cryptoerror(LOG_STDERR, gettext("Unrecognized hash.\n")); return (PK_ERR_USAGE); } break; default: return (PK_ERR_USAGE); } } /* No additional args allowed. */ argc -= optind_av; argv += optind_av; if (argc) { return (PK_ERR_USAGE); } if ((rv = kmf_initialize(&kmfhandle, NULL, NULL)) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Error initializing KMF\n")); return (PK_ERR_USAGE); } /* Assume keystore = PKCS#11 if not specified. */ if (kstype == 0) kstype = KMF_KEYSTORE_PK11TOKEN; if ((kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN)) { if (interactive && EMPTYSTRING(certlabel)) { (void) get_certlabel(&certlabel); } /* It better not be empty now */ if (EMPTYSTRING(certlabel)) { cryptoerror(LOG_STDERR, gettext("A label must be " "specified to create a self-signed certificate." "\n")); return (PK_ERR_USAGE); } } else if (kstype == KMF_KEYSTORE_OPENSSL && EMPTYSTRING(outcert)) { cryptoerror(LOG_STDERR, gettext("A certificate filename must " "be specified to create a self-signed certificate.\n")); return (PK_ERR_USAGE); } DIR_OPTION_CHECK(kstype, dir); if (format && (fmt = Str2Format(format)) == KMF_FORMAT_UNDEF) { cryptoerror(LOG_STDERR, gettext("Error parsing format string (%s).\n"), format); return (PK_ERR_USAGE); } if (Str2Lifetime(lifetime, <ime) != 0) { cryptoerror(LOG_STDERR, gettext("Error parsing lifetime string\n")); return (PK_ERR_USAGE); } if (Str2KeyType(keytype, hashoid, &keyAlg, &sigAlg) != 0) { cryptoerror(LOG_STDERR, gettext("Unsupported key/hash combination (%s/%s).\n"), keytype, (hashname ? hashname : "none")); return (PK_ERR_USAGE); } if (curveoid != NULL && keyAlg != KMF_ECDSA) { cryptoerror(LOG_STDERR, gettext("EC curves are only " "valid for EC keytypes.\n")); return (PK_ERR_USAGE); } if (keyAlg == KMF_ECDSA && curveoid == NULL) { cryptoerror(LOG_STDERR, gettext("A curve must be " "specifed when using EC keys.\n")); return (PK_ERR_USAGE); } /* Adjust default keylength for NSS and DSA */ if (keyAlg == KMF_DSA && !y_flag && kstype == KMF_KEYSTORE_NSS) keylen = 1024; /* * Check the subject name. * If interactive is true, get it now interactively. */ if (interactive) { subname = NULL; if (get_subname(&subname) != KMF_OK || subname == NULL) { cryptoerror(LOG_STDERR, gettext("Failed to get the " "subject name interactively.\n")); return (PK_ERR_USAGE); } if (serstr == NULL) { (void) get_serial(&serstr); } } else { if (EMPTYSTRING(subject)) { cryptoerror(LOG_STDERR, gettext("A subject name or " "-i must be specified to create a self-signed " "certificate.\n")); return (PK_ERR_USAGE); } else { subname = strdup(subject); if (subname == NULL) { cryptoerror(LOG_STDERR, gettext("Out of memory.\n")); return (PK_ERR_SYSTEM); } } } if (serstr == NULL) { (void) fprintf(stderr, gettext("A serial number " "must be specified as a hex number when creating" " a self-signed certificate " "(ex: serial=0x0102030405feedface)\n")); rv = PK_ERR_USAGE; goto end; } else { uchar_t *bytes = NULL; size_t bytelen; rv = kmf_hexstr_to_bytes((uchar_t *)serstr, &bytes, &bytelen); if (rv != KMF_OK || bytes == NULL) { (void) fprintf(stderr, gettext("serial number " "must be specified as a hex number " "(ex: 0x0102030405ffeeddee)\n")); rv = PK_ERR_USAGE; goto end; } serial.val = bytes; serial.len = bytelen; } if (altname != NULL) { rv = verify_altname(altname, &alttype, &altcrit); if (rv != KMF_OK) { (void) fprintf(stderr, gettext("Subject AltName " "must be specified as a name=value pair. " "See the man page for details.\n")); rv = PK_ERR_USAGE; goto end; } else { /* advance the altname past the '=' sign */ char *p = strchr(altname, '='); if (p != NULL) altname = p + 1; } } if (keyusagestr != NULL) { rv = verify_keyusage(keyusagestr, &kubits, &kucrit); if (rv != KMF_OK) { (void) fprintf(stderr, gettext("KeyUsage " "must be specified as a comma-separated list. " "See the man page for details.\n")); rv = PK_ERR_USAGE; goto end; } } if (ekustr != NULL) { rv = verify_ekunames(ekustr, &ekulist); if (rv != KMF_OK) { (void) fprintf(stderr, gettext("EKUs must " "be specified as a comma-separated list. " "See the man page for details.\n")); rv = PK_ERR_USAGE; goto end; } } if (keyAlg == KMF_ECDSA && kstype == KMF_KEYSTORE_OPENSSL) { (void) fprintf(stderr, gettext("ECC certificates are" "only supported with the pkcs11 and nss keystores\n")); rv = PK_ERR_USAGE; goto end; } if (kstype == KMF_KEYSTORE_NSS || kstype == KMF_KEYSTORE_PK11TOKEN) { if (tokenname == NULL || !strlen(tokenname)) { if (kstype == KMF_KEYSTORE_NSS) { tokenname = "internal"; } else { tokenname = PK_DEFAULT_PK11TOKEN; } } (void) get_token_password(kstype, tokenname, &tokencred); } if (kstype == KMF_KEYSTORE_NSS) { if (dir == NULL) dir = PK_DEFAULT_DIRECTORY; rv = gencert_nss(kmfhandle, tokenname, subname, altname, alttype, altcrit, certlabel, dir, prefix, keyAlg, sigAlg, keylen, trust, ltime, &serial, kubits, kucrit, &tokencred, ekulist, curveoid); } else if (kstype == KMF_KEYSTORE_PK11TOKEN) { rv = gencert_pkcs11(kmfhandle, tokenname, subname, altname, alttype, altcrit, certlabel, keyAlg, sigAlg, keylen, ltime, &serial, kubits, kucrit, &tokencred, ekulist, curveoid); } else if (kstype == KMF_KEYSTORE_OPENSSL) { rv = gencert_file(kmfhandle, keyAlg, sigAlg, keylen, fmt, ltime, subname, altname, alttype, altcrit, &serial, kubits, kucrit, outcert, outkey, ekulist); } if (rv != KMF_OK) display_error(kmfhandle, rv, gettext("Error creating certificate and keypair")); end: if (ekulist != NULL) free_eku_list(ekulist); if (subname) free(subname); if (tokencred.cred != NULL) free(tokencred.cred); if (serial.val != NULL) free(serial.val); (void) kmf_finalize(kmfhandle); return (rv); }
static int gencert_file(KMF_HANDLE_T kmfhandle, KMF_KEY_ALG keyAlg, KMF_ALGORITHM_INDEX sigAlg, int keylen, KMF_ENCODE_FORMAT fmt, uint32_t ltime, char *subject, char *altname, KMF_GENERALNAMECHOICES alttype, int altcrit, KMF_BIGINT *serial, uint16_t kubits, int kucrit, char *outcert, char *outkey, EKU_LIST *ekulist) { KMF_RETURN kmfrv; KMF_KEY_HANDLE pubk, prik; KMF_X509_CERTIFICATE signedCert; KMF_X509_NAME certSubject; KMF_X509_NAME certIssuer; KMF_DATA x509DER; char *fullcertpath = NULL; char *fullkeypath = NULL; KMF_KEYSTORE_TYPE kstype = KMF_KEYSTORE_OPENSSL; KMF_ATTRIBUTE attrlist[10]; int numattr = 0; (void) memset(&signedCert, 0, sizeof (signedCert)); (void) memset(&certSubject, 0, sizeof (certSubject)); (void) memset(&certIssuer, 0, sizeof (certIssuer)); (void) memset(&x509DER, 0, sizeof (x509DER)); if (EMPTYSTRING(outcert) || EMPTYSTRING(outkey)) { cryptoerror(LOG_STDERR, gettext("No output file was specified for " "the cert or key\n")); return (PK_ERR_USAGE); } fullcertpath = strdup(outcert); if (verify_file(fullcertpath)) { cryptoerror(LOG_STDERR, gettext("Cannot write the indicated output " "certificate file (%s).\n"), fullcertpath); free(fullcertpath); return (PK_ERR_USAGE); } /* If the subject name cannot be parsed, flag it now and exit */ if (kmf_dn_parser(subject, &certSubject) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Subject name cannot be parsed (%s)\n"), subject); return (PK_ERR_USAGE); } /* For a self-signed cert, the issuser and subject are the same */ if (kmf_dn_parser(subject, &certIssuer) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Subject name cannot be parsed (%s)\n"), subject); kmf_free_dn(&certSubject); return (PK_ERR_USAGE); } /* * Share the "genkeypair" routine for creating the keypair. */ kmfrv = genkeypair_file(kmfhandle, keyAlg, keylen, fmt, outkey, &prik, &pubk); if (kmfrv != KMF_OK) return (kmfrv); SET_VALUE(kmf_set_cert_pubkey(kmfhandle, &pubk, &signedCert), "keypair"); SET_VALUE(kmf_set_cert_version(&signedCert, 2), "version number"); SET_VALUE(kmf_set_cert_serial(&signedCert, serial), "serial number"); SET_VALUE(kmf_set_cert_validity(&signedCert, NULL, ltime), "validity time"); SET_VALUE(kmf_set_cert_sig_alg(&signedCert, sigAlg), "signature algorithm"); SET_VALUE(kmf_set_cert_subject(&signedCert, &certSubject), "subject name"); SET_VALUE(kmf_set_cert_issuer(&signedCert, &certIssuer), "issuer name"); if (altname != NULL) SET_VALUE(kmf_set_cert_subject_altname(&signedCert, altcrit, alttype, altname), "subjectAltName"); if (kubits != 0) SET_VALUE(kmf_set_cert_ku(&signedCert, kucrit, kubits), "KeyUsage"); if (ekulist != NULL) { int i; for (i = 0; kmfrv == KMF_OK && i < ekulist->eku_count; i++) { SET_VALUE(kmf_add_cert_eku(&signedCert, &ekulist->ekulist[i], ekulist->critlist[i]), "Extended Key Usage"); } } /* * Construct attributes for the kmf_sign_cert operation. */ numattr = 0; kmf_set_attr_at_index(attrlist, numattr, KMF_KEYSTORE_TYPE_ATTR, &kstype, sizeof (kstype)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_KEY_HANDLE_ATTR, &prik, sizeof (KMF_KEY_HANDLE_ATTR)); numattr++; /* cert data that is to be signed */ kmf_set_attr_at_index(attrlist, numattr, KMF_X509_CERTIFICATE_ATTR, &signedCert, sizeof (KMF_X509_CERTIFICATE)); numattr++; /* output buffer for the signed cert */ kmf_set_attr_at_index(attrlist, numattr, KMF_CERT_DATA_ATTR, &x509DER, sizeof (KMF_DATA)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_ALGORITHM_INDEX_ATTR, &sigAlg, sizeof (sigAlg)); numattr++; if ((kmfrv = kmf_sign_cert(kmfhandle, numattr, attrlist)) != KMF_OK) { goto cleanup; } /* * Store the cert in the DB. */ numattr = 0; kmf_set_attr_at_index(attrlist, numattr, KMF_KEYSTORE_TYPE_ATTR, &kstype, sizeof (kstype)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_CERT_DATA_ATTR, &x509DER, sizeof (KMF_DATA)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_CERT_FILENAME_ATTR, fullcertpath, strlen(fullcertpath)); numattr++; kmf_set_attr_at_index(attrlist, numattr, KMF_ENCODE_FORMAT_ATTR, &fmt, sizeof (fmt)); numattr++; kmfrv = kmf_store_cert(kmfhandle, numattr, attrlist); cleanup: if (fullkeypath != NULL) free(fullkeypath); if (fullcertpath != NULL) free(fullcertpath); kmf_free_data(&x509DER); kmf_free_dn(&certSubject); kmf_free_dn(&certIssuer); return (kmfrv); }
/* * Retrieve URL, via the proxy in $proxyvar if necessary. * Modifies the string argument given. * Returns -1 on failure, 0 on success */ static int url_get(const char *origline, const char *proxyenv, const char *outfile) { char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST], *cp, *portnum, *path, ststr[4]; char *hosttail, *cause = "unknown", *newline, *host, *port, *buf = NULL; char *epath, *redirurl, *loctail, *h, *p; int error, i, isftpurl = 0, isfileurl = 0, isredirect = 0, rval = -1; struct addrinfo hints, *res0, *res, *ares = NULL; const char * volatile savefile; char * volatile proxyurl = NULL; char *cookie = NULL; volatile int s = -1, out; volatile sig_t oldintr, oldinti; FILE *fin = NULL; off_t hashbytes; const char *errstr; ssize_t len, wlen; #ifndef SMALL char *sslpath = NULL, *sslhost = NULL; char *locbase, *full_host = NULL, *auth = NULL; const char *scheme; int ishttpsurl = 0; SSL_CTX *ssl_ctx = NULL; #endif /* !SMALL */ SSL *ssl = NULL; int status; int save_errno; const size_t buflen = 128 * 1024; direction = "received"; newline = strdup(origline); if (newline == NULL) errx(1, "Can't allocate memory to parse URL"); if (strncasecmp(newline, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) { host = newline + sizeof(HTTP_URL) - 1; #ifndef SMALL scheme = HTTP_URL; #endif /* !SMALL */ } else if (strncasecmp(newline, FTP_URL, sizeof(FTP_URL) - 1) == 0) { host = newline + sizeof(FTP_URL) - 1; isftpurl = 1; #ifndef SMALL scheme = FTP_URL; #endif /* !SMALL */ } else if (strncasecmp(newline, FILE_URL, sizeof(FILE_URL) - 1) == 0) { host = newline + sizeof(FILE_URL) - 1; isfileurl = 1; #ifndef SMALL scheme = FILE_URL; } else if (strncasecmp(newline, HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0) { host = newline + sizeof(HTTPS_URL) - 1; ishttpsurl = 1; scheme = HTTPS_URL; #endif /* !SMALL */ } else errx(1, "url_get: Invalid URL '%s'", newline); if (isfileurl) { path = host; } else { path = strchr(host, '/'); /* Find path */ if (EMPTYSTRING(path)) { if (outfile) { /* No slash, but */ path=strchr(host,'\0'); /* we have outfile. */ goto noslash; } if (isftpurl) goto noftpautologin; warnx("No `/' after host (use -o): %s", origline); goto cleanup_url_get; } *path++ = '\0'; if (EMPTYSTRING(path) && !outfile) { if (isftpurl) goto noftpautologin; warnx("No filename after host (use -o): %s", origline); goto cleanup_url_get; } } noslash: #ifndef SMALL /* * Look for auth header in host, since now host does not * contain the path. Basic auth from RFC 2617, valid * characters for path are in RFC 3986 section 3.3. */ if (proxyenv == NULL && (!strcmp(scheme, HTTP_URL) || !strcmp(scheme, HTTPS_URL))) { if ((p = strchr(host, '@')) != NULL) { size_t authlen = (strlen(host) + 5) * 4 / 3; *p = 0; /* Kill @ */ if ((auth = malloc(authlen)) == NULL) err(1, "Can't allocate memory for " "authorization"); if (b64_ntop(host, strlen(host), auth, authlen) == -1) errx(1, "error in base64 encoding"); host = p + 1; } } #endif /* SMALL */ if (outfile) savefile = outfile; else { if (path[strlen(path) - 1] == '/') /* Consider no file */ savefile = NULL; /* after dir invalid. */ else savefile = basename(path); } if (EMPTYSTRING(savefile)) { if (isftpurl) goto noftpautologin; warnx("No filename after directory (use -o): %s", origline); goto cleanup_url_get; } #ifndef SMALL if (resume && pipeout) { warnx("can't append to stdout"); goto cleanup_url_get; } #endif /* !SMALL */ if (!isfileurl && proxyenv != NULL) { /* use proxy */ #ifndef SMALL if (ishttpsurl) { sslpath = strdup(path); sslhost = strdup(host); if (! sslpath || ! sslhost) errx(1, "Can't allocate memory for https path/host."); } #endif /* !SMALL */ proxyurl = strdup(proxyenv); if (proxyurl == NULL) errx(1, "Can't allocate memory for proxy URL."); if (strncasecmp(proxyurl, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) host = proxyurl + sizeof(HTTP_URL) - 1; else if (strncasecmp(proxyurl, FTP_URL, sizeof(FTP_URL) - 1) == 0) host = proxyurl + sizeof(FTP_URL) - 1; else { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } if (EMPTYSTRING(host)) { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } if (*--path == '\0') *path = '/'; /* add / back to real path */ path = strchr(host, '/'); /* remove trailing / on host */ if (!EMPTYSTRING(path)) *path++ = '\0'; /* i guess this ++ is useless */ path = strchr(host, '@'); /* look for credentials in proxy */ if (!EMPTYSTRING(path)) { *path = '\0'; cookie = strchr(host, ':'); if (EMPTYSTRING(cookie)) { warnx("Malformed proxy URL: %s", proxyenv); goto cleanup_url_get; } cookie = malloc(COOKIE_MAX_LEN); if (cookie == NULL) errx(1, "out of memory"); if (b64_ntop(host, strlen(host), cookie, COOKIE_MAX_LEN) == -1) errx(1, "error in base64 encoding"); *path = '@'; /* restore @ in proxyurl */ /* * This removes the password from proxyurl, * filling with stars */ for (host = 1 + strchr(proxyurl + 5, ':'); *host != '@'; host++) *host = '*'; host = path + 1; } path = newline; } if (isfileurl) { struct stat st; s = open(path, O_RDONLY); if (s == -1) { warn("Can't open file %s", path); goto cleanup_url_get; } if (fstat(s, &st) == -1) filesize = -1; else filesize = st.st_size; /* Open the output file. */ if (!pipeout) { #ifndef SMALL if (resume) out = open(savefile, O_CREAT | O_WRONLY | O_APPEND, 0666); else #endif /* !SMALL */ out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); if (out < 0) { warn("Can't open %s", savefile); goto cleanup_url_get; } } else out = fileno(stdout); #ifndef SMALL if (resume) { if (fstat(out, &st) == -1) { warn("Can't fstat %s", savefile); goto cleanup_url_get; } if (lseek(s, st.st_size, SEEK_SET) == -1) { warn("Can't lseek %s", path); goto cleanup_url_get; } restart_point = st.st_size; } #endif /* !SMALL */ /* Trap signals */ oldintr = NULL; oldinti = NULL; if (setjmp(httpabort)) { if (oldintr) (void)signal(SIGINT, oldintr); if (oldinti) (void)signal(SIGINFO, oldinti); goto cleanup_url_get; } oldintr = signal(SIGINT, abortfile); bytes = 0; hashbytes = mark; progressmeter(-1, path); if ((buf = malloc(buflen)) == NULL) errx(1, "Can't allocate memory for transfer buffer"); /* Finally, suck down the file. */ i = 0; oldinti = signal(SIGINFO, psummary); while ((len = read(s, buf, buflen)) > 0) { bytes += len; for (cp = buf; len > 0; len -= i, cp += i) { if ((i = write(out, cp, len)) == -1) { warn("Writing %s", savefile); signal(SIGINFO, oldinti); goto cleanup_url_get; } else if (i == 0) break; } if (hash && !progress) { while (bytes >= hashbytes) { (void)putc('#', ttyout); hashbytes += mark; } (void)fflush(ttyout); } } signal(SIGINFO, oldinti); if (hash && !progress && bytes > 0) { if (bytes < mark) (void)putc('#', ttyout); (void)putc('\n', ttyout); (void)fflush(ttyout); } if (len != 0) { warn("Reading from file"); goto cleanup_url_get; } progressmeter(1, NULL); if (verbose) ptransfer(0); (void)signal(SIGINT, oldintr); rval = 0; goto cleanup_url_get; } if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL && (hosttail[1] == '\0' || hosttail[1] == ':')) { host++; *hosttail++ = '\0'; #ifndef SMALL if (asprintf(&full_host, "[%s]", host) == -1) errx(1, "Cannot allocate memory for hostname"); #endif /* !SMALL */ } else hosttail = host; portnum = strrchr(hosttail, ':'); /* find portnum */ if (portnum != NULL) *portnum++ = '\0'; #ifndef SMALL if (full_host == NULL) if ((full_host = strdup(host)) == NULL) errx(1, "Cannot allocate memory for hostname"); if (debug) fprintf(ttyout, "host %s, port %s, path %s, " "save as %s, auth %s.\n", host, portnum, path, savefile, auth); #endif /* !SMALL */ memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; #ifndef SMALL port = portnum ? portnum : (ishttpsurl ? httpsport : httpport); #else /* !SMALL */ port = portnum ? portnum : httpport; #endif /* !SMALL */ error = getaddrinfo(host, port, &hints, &res0); /* * If the services file is corrupt/missing, fall back * on our hard-coded defines. */ if (error == EAI_SERVICE && port == httpport) { snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT); error = getaddrinfo(host, pbuf, &hints, &res0); #ifndef SMALL } else if (error == EAI_SERVICE && port == httpsport) { snprintf(pbuf, sizeof(pbuf), "%d", HTTPS_PORT); error = getaddrinfo(host, pbuf, &hints, &res0); #endif /* !SMALL */ } if (error) { warnx("%s: %s", gai_strerror(error), host); goto cleanup_url_get; } #ifndef SMALL if (srcaddr) { hints.ai_flags |= AI_NUMERICHOST; error = getaddrinfo(srcaddr, NULL, &hints, &ares); if (error) { warnx("%s: %s", gai_strerror(error), srcaddr); goto cleanup_url_get; } } #endif /* !SMALL */ s = -1; for (res = res0; res; res = res->ai_next) { if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) strlcpy(hbuf, "(unknown)", sizeof(hbuf)); if (verbose) fprintf(ttyout, "Trying %s...\n", hbuf); s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (s == -1) { cause = "socket"; continue; } #ifndef SMALL if (srcaddr) { if (ares->ai_family != res->ai_family) { close(s); s = -1; errno = EINVAL; cause = "bind"; continue; } if (bind(s, ares->ai_addr, ares->ai_addrlen) < 0) { save_errno = errno; close(s); errno = save_errno; s = -1; cause = "bind"; continue; } } #endif /* !SMALL */ again: if (connect(s, res->ai_addr, res->ai_addrlen) < 0) { if (errno == EINTR) goto again; save_errno = errno; close(s); errno = save_errno; s = -1; cause = "connect"; continue; } /* get port in numeric */ if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0, pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0) port = pbuf; else port = NULL; #ifndef SMALL if (proxyenv && sslhost) proxy_connect(s, sslhost, cookie); #endif /* !SMALL */ break; } freeaddrinfo(res0); #ifndef SMALL if (srcaddr) freeaddrinfo(ares); #endif /* !SMALL */ if (s < 0) { warn("%s", cause); goto cleanup_url_get; } #ifndef SMALL if (ishttpsurl) { union { struct in_addr ip4; struct in6_addr ip6; } addrbuf; if (proxyenv && sslpath) { ishttpsurl = 0; proxyurl = NULL; path = sslpath; } SSL_library_init(); SSL_load_error_strings(); ssl_ctx = SSL_CTX_new(SSLv23_client_method()); if (ssl_ctx == NULL) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } if (ssl_verify) { if (ssl_ca_file == NULL && ssl_ca_path == NULL) ssl_ca_file = _PATH_SSL_CAFILE; if (SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_file, ssl_ca_path) != 1) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); if (ssl_verify_depth != -1) SSL_CTX_set_verify_depth(ssl_ctx, ssl_verify_depth); } if (ssl_ciphers != NULL && SSL_CTX_set_cipher_list(ssl_ctx, ssl_ciphers) == -1) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } ssl = SSL_new(ssl_ctx); if (ssl == NULL) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } if (SSL_set_fd(ssl, s) == 0) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } /* * RFC4366 (SNI): Literal IPv4 and IPv6 addresses are not * permitted in "HostName". */ if (inet_pton(AF_INET, host, &addrbuf) != 1 && inet_pton(AF_INET6, host, &addrbuf) != 1) { if (SSL_set_tlsext_host_name(ssl, host) == 0) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } } if (SSL_connect(ssl) <= 0) { ERR_print_errors_fp(ttyout); goto cleanup_url_get; } if (ssl_verify) { X509 *cert; cert = SSL_get_peer_certificate(ssl); if (cert == NULL) { fprintf(ttyout, "%s: no server certificate\n", getprogname()); goto cleanup_url_get; } if (ssl_check_hostname(cert, host) != 0) { fprintf(ttyout, "%s: host `%s' not present in" " server certificate\n", getprogname(), host); goto cleanup_url_get; } X509_free(cert); } } else { fin = fdopen(s, "r+"); } #else /* !SMALL */ fin = fdopen(s, "r+"); #endif /* !SMALL */ if (verbose) fprintf(ttyout, "Requesting %s", origline); /* * Construct and send the request. Proxy requests don't want leading /. */ #ifndef SMALL cookie_get(host, path, ishttpsurl, &buf); #endif /* !SMALL */ epath = url_encode(path); if (proxyurl) { if (verbose) fprintf(ttyout, " (via %s)\n", proxyurl); /* * Host: directive must use the destination host address for * the original URI (path). We do not attach it at this moment. */ if (cookie) ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n" "Proxy-Authorization: Basic %s%s\r\n%s\r\n\r\n", epath, cookie, buf ? buf : "", HTTP_USER_AGENT); else ftp_printf(fin, ssl, "GET %s HTTP/1.0\r\n%s%s\r\n\r\n", epath, buf ? buf : "", HTTP_USER_AGENT); } else { #ifndef SMALL if (resume) { struct stat stbuf; if (stat(savefile, &stbuf) == 0) restart_point = stbuf.st_size; else restart_point = 0; } if (auth) { ftp_printf(fin, ssl, "GET /%s %s\r\nAuthorization: Basic %s\r\nHost: ", epath, restart_point ? "HTTP/1.1\r\nConnection: close" : "HTTP/1.0", auth); free(auth); auth = NULL; } else #endif /* SMALL */ ftp_printf(fin, ssl, "GET /%s %s\r\nHost: ", epath, #ifndef SMALL restart_point ? "HTTP/1.1\r\nConnection: close" : #endif /* !SMALL */ "HTTP/1.0"); if (strchr(host, ':')) { /* * strip off scoped address portion, since it's * local to node */ h = strdup(host); if (h == NULL) errx(1, "Can't allocate memory."); if ((p = strchr(h, '%')) != NULL) *p = '\0'; ftp_printf(fin, ssl, "[%s]", h); free(h); } else ftp_printf(fin, ssl, "%s", host); /* * Send port number only if it's specified and does not equal * 80. Some broken HTTP servers get confused if you explicitly * send them the port number. */ #ifndef SMALL if (port && strcmp(port, (ishttpsurl ? "443" : "80")) != 0) ftp_printf(fin, ssl, ":%s", port); if (restart_point) ftp_printf(fin, ssl, "\r\nRange: bytes=%lld-", (long long)restart_point); #else /* !SMALL */ if (port && strcmp(port, "80") != 0) ftp_printf(fin, ssl, ":%s", port); #endif /* !SMALL */ ftp_printf(fin, ssl, "\r\n%s%s\r\n\r\n", buf ? buf : "", HTTP_USER_AGENT); if (verbose) fprintf(ttyout, "\n"); } free(epath); #ifndef SMALL free(buf); #endif /* !SMALL */ buf = NULL; if (fin != NULL && fflush(fin) == EOF) { warn("Writing HTTP request"); goto cleanup_url_get; } if ((buf = ftp_readline(fin, ssl, &len)) == NULL) { warn("Receiving HTTP reply"); goto cleanup_url_get; } while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) buf[--len] = '\0'; #ifndef SMALL if (debug) fprintf(ttyout, "received '%s'\n", buf); #endif /* !SMALL */ cp = strchr(buf, ' '); if (cp == NULL) goto improper; else cp++; strlcpy(ststr, cp, sizeof(ststr)); status = strtonum(ststr, 200, 416, &errstr); if (errstr) { warnx("Error retrieving file: %s", cp); goto cleanup_url_get; } switch (status) { case 200: /* OK */ #ifndef SMALL /* * When we request a partial file, and we receive an HTTP 200 * it is a good indication that the server doesn't support * range requests, and is about to send us the entire file. * If the restart_point == 0, then we are not actually * requesting a partial file, and an HTTP 200 is appropriate. */ if (resume && restart_point != 0) { warnx("Server does not support resume."); restart_point = resume = 0; } /* FALLTHROUGH */ case 206: /* Partial Content */ #endif /* !SMALL */ break; case 301: /* Moved Permanently */ case 302: /* Found */ case 303: /* See Other */ case 307: /* Temporary Redirect */ isredirect++; if (redirect_loop++ > 10) { warnx("Too many redirections requested"); goto cleanup_url_get; } break; #ifndef SMALL case 416: /* Requested Range Not Satisfiable */ warnx("File is already fully retrieved."); goto cleanup_url_get; #endif /* !SMALL */ default: warnx("Error retrieving file: %s", cp); goto cleanup_url_get; } /* * Read the rest of the header. */ free(buf); filesize = -1; for (;;) { if ((buf = ftp_readline(fin, ssl, &len)) == NULL) { warn("Receiving HTTP reply"); goto cleanup_url_get; } while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) buf[--len] = '\0'; if (len == 0) break; #ifndef SMALL if (debug) fprintf(ttyout, "received '%s'\n", buf); #endif /* !SMALL */ /* Look for some headers */ cp = buf; #define CONTENTLEN "Content-Length: " if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) { size_t s; cp += sizeof(CONTENTLEN) - 1; if ((s = strcspn(cp, " \t"))) *(cp+s) = 0; filesize = strtonum(cp, 0, LLONG_MAX, &errstr); if (errstr != NULL) goto improper; #ifndef SMALL if (restart_point) filesize += restart_point; #endif /* !SMALL */ #define LOCATION "Location: " } else if (isredirect && strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) { cp += sizeof(LOCATION) - 1; if (strstr(cp, "://") == NULL) { #ifdef SMALL errx(1, "Relative redirect not supported"); #else /* SMALL */ if (*cp == '/') { locbase = NULL; cp++; } else { locbase = strdup(path); if (locbase == NULL) errx(1, "Can't allocate memory" " for location base"); loctail = strchr(locbase, '#'); if (loctail != NULL) *loctail = '\0'; loctail = strchr(locbase, '?'); if (loctail != NULL) *loctail = '\0'; loctail = strrchr(locbase, '/'); if (loctail == NULL) { free(locbase); locbase = NULL; } else loctail[1] = '\0'; } /* Contruct URL from relative redirect */ if (asprintf(&redirurl, "%s%s%s%s/%s%s", scheme, full_host, portnum ? ":" : "", portnum ? portnum : "", locbase ? locbase : "", cp) == -1) errx(1, "Cannot build " "redirect URL"); free(locbase); #endif /* SMALL */ } else if ((redirurl = strdup(cp)) == NULL) errx(1, "Cannot allocate memory for URL"); loctail = strchr(redirurl, '#'); if (loctail != NULL) *loctail = '\0'; if (verbose) fprintf(ttyout, "Redirected to %s\n", redirurl); if (fin != NULL) fclose(fin); else if (s != -1) close(s); rval = url_get(redirurl, proxyenv, savefile); free(redirurl); goto cleanup_url_get; } free(buf); } /* Open the output file. */ if (!pipeout) { #ifndef SMALL if (resume) out = open(savefile, O_CREAT | O_WRONLY | O_APPEND, 0666); else #endif /* !SMALL */ out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); if (out < 0) { warn("Can't open %s", savefile); goto cleanup_url_get; } } else out = fileno(stdout); /* Trap signals */ oldintr = NULL; oldinti = NULL; if (setjmp(httpabort)) { if (oldintr) (void)signal(SIGINT, oldintr); if (oldinti) (void)signal(SIGINFO, oldinti); goto cleanup_url_get; } oldintr = signal(SIGINT, aborthttp); bytes = 0; hashbytes = mark; progressmeter(-1, path); free(buf); /* Finally, suck down the file. */ if ((buf = malloc(buflen)) == NULL) errx(1, "Can't allocate memory for transfer buffer"); i = 0; len = 1; oldinti = signal(SIGINFO, psummary); while (len > 0) { len = ftp_read(fin, ssl, buf, buflen); bytes += len; for (cp = buf, wlen = len; wlen > 0; wlen -= i, cp += i) { if ((i = write(out, cp, wlen)) == -1) { warn("Writing %s", savefile); signal(SIGINFO, oldinti); goto cleanup_url_get; } else if (i == 0) break; } if (hash && !progress) { while (bytes >= hashbytes) { (void)putc('#', ttyout); hashbytes += mark; } (void)fflush(ttyout); } } signal(SIGINFO, oldinti); if (hash && !progress && bytes > 0) { if (bytes < mark) (void)putc('#', ttyout); (void)putc('\n', ttyout); (void)fflush(ttyout); } if (len != 0) { warn("Reading from socket"); goto cleanup_url_get; } progressmeter(1, NULL); if ( #ifndef SMALL !resume && #endif /* !SMALL */ filesize != -1 && len == 0 && bytes != filesize) { if (verbose) fputs("Read short file.\n", ttyout); goto cleanup_url_get; } if (verbose) ptransfer(0); (void)signal(SIGINT, oldintr); rval = 0; goto cleanup_url_get; noftpautologin: warnx( "Auto-login using ftp URLs isn't supported when using $ftp_proxy"); goto cleanup_url_get; improper: warnx("Improper response from %s", host); cleanup_url_get: #ifndef SMALL if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); } free(full_host); free(auth); #endif /* !SMALL */ if (fin != NULL) fclose(fin); else if (s != -1) close(s); free(buf); free(proxyurl); free(newline); free(cookie); return (rval); }
int pk_download(int argc, char *argv[]) { int rv; int opt; extern int optind_av; extern char *optarg_av; int oclass = 0; char *url = NULL; char *http_proxy = NULL; char *dir = NULL; char *outfile = NULL; char *proxy = NULL; int proxy_port = 0; KMF_HANDLE_T kmfhandle = NULL; KMF_ENCODE_FORMAT format; KMF_RETURN ch_rv = KMF_OK; char *fullpath = NULL; KMF_DATA cert = { 0, NULL }; KMF_DATA cert_der = { 0, NULL }; while ((opt = getopt_av(argc, argv, "t:(objtype)u:(url)h:(http_proxy)o:(outfile)d:(dir)")) != EOF) { if (EMPTYSTRING(optarg_av)) return (PK_ERR_USAGE); switch (opt) { case 't': if (oclass) return (PK_ERR_USAGE); oclass = OT2Int(optarg_av); if (!(oclass & (PK_CERT_OBJ | PK_CRL_OBJ))) return (PK_ERR_USAGE); break; case 'u': if (url) return (PK_ERR_USAGE); url = optarg_av; break; case 'h': if (http_proxy) return (PK_ERR_USAGE); http_proxy = optarg_av; break; case 'o': if (outfile) return (PK_ERR_USAGE); outfile = optarg_av; break; case 'd': if (dir) return (PK_ERR_USAGE); dir = optarg_av; break; default: cryptoerror(LOG_STDERR, gettext( "unrecognized download option '%s'\n"), argv[optind_av]); return (PK_ERR_USAGE); } } /* No additional args allowed. */ argc -= optind_av; argv += optind_av; if (argc) { return (PK_ERR_USAGE); } /* Check the dir and outfile options */ if (outfile == NULL) { /* If outfile is not specified, use the basename of URI */ outfile = basename(url); } fullpath = get_fullpath(dir, outfile); if (fullpath == NULL) { cryptoerror(LOG_STDERR, gettext("Incorrect dir or outfile " "option value \n")); return (PK_ERR_USAGE); } /* Check if the file exists and might be overwritten. */ if (verify_file(fullpath) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Warning: file \"%s\" exists, " "will be overwritten."), fullpath); if (yesno(gettext("Continue with download? "), gettext("Respond with yes or no.\n"), B_FALSE) == B_FALSE) { return (0); } } /* URI MUST be specified */ if (url == NULL) { cryptoerror(LOG_STDERR, gettext("A URL must be specified\n")); rv = PK_ERR_USAGE; goto end; } /* * Get the http proxy from the command "http_proxy" option or the * environment variable. The command option has a higher priority. */ if (http_proxy == NULL) http_proxy = getenv("http_proxy"); if (http_proxy != NULL) { char *ptmp = http_proxy; char *proxy_port_s; if (strncasecmp(ptmp, "http://", 7) == 0) ptmp += 7; /* skip the scheme prefix */ proxy = strtok(ptmp, ":"); proxy_port_s = strtok(NULL, "\0"); if (proxy_port_s != NULL) proxy_port = strtol(proxy_port_s, NULL, 0); else proxy_port = 8080; } /* If objtype is not specified, default to CRL */ if (oclass == 0) { oclass = PK_CRL_OBJ; } if ((rv = kmf_initialize(&kmfhandle, NULL, NULL)) != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Error initializing KMF\n")); rv = PK_ERR_USAGE; goto end; } /* Now we are ready to download */ if (oclass & PK_CRL_OBJ) { rv = kmf_download_crl(kmfhandle, url, proxy, proxy_port, 30, fullpath, &format); } else if (oclass & PK_CERT_OBJ) { rv = kmf_download_cert(kmfhandle, url, proxy, proxy_port, 30, fullpath, &format); } if (rv != KMF_OK) { switch (rv) { case KMF_ERR_BAD_URI: cryptoerror(LOG_STDERR, gettext("Error in parsing URI\n")); rv = PK_ERR_USAGE; break; case KMF_ERR_OPEN_FILE: cryptoerror(LOG_STDERR, gettext("Error in opening file\n")); rv = PK_ERR_USAGE; break; case KMF_ERR_WRITE_FILE: cryptoerror(LOG_STDERR, gettext("Error in writing file\n")); rv = PK_ERR_USAGE; break; case KMF_ERR_BAD_CRLFILE: cryptoerror(LOG_STDERR, gettext("Not a CRL file\n")); rv = PK_ERR_USAGE; break; case KMF_ERR_BAD_CERTFILE: cryptoerror(LOG_STDERR, gettext("Not a certificate file\n")); rv = PK_ERR_USAGE; break; case KMF_ERR_MEMORY: cryptoerror(LOG_STDERR, gettext("Not enough memory\n")); rv = PK_ERR_SYSTEM; break; default: cryptoerror(LOG_STDERR, gettext("Error in downloading the file.\n")); rv = PK_ERR_SYSTEM; break; } goto end; } /* * If the file is successfully downloaded, we also check the date. * If the downloaded file is outdated, give a warning. */ if (oclass & PK_CRL_OBJ) { ch_rv = kmf_check_crl_date(kmfhandle, fullpath); } else { /* certificate */ ch_rv = kmf_read_input_file(kmfhandle, fullpath, &cert); if (ch_rv != KMF_OK) goto end; if (format == KMF_FORMAT_PEM) { int len; ch_rv = kmf_pem_to_der(cert.Data, cert.Length, &cert_der.Data, &len); if (ch_rv != KMF_OK) goto end; cert_der.Length = (size_t)len; } ch_rv = kmf_check_cert_date(kmfhandle, format == KMF_FORMAT_ASN1 ? &cert : &cert_der); } end: if (ch_rv == KMF_ERR_VALIDITY_PERIOD) { cryptoerror(LOG_STDERR, gettext("Warning: the downloaded file is expired.\n")); } else if (ch_rv != KMF_OK) { cryptoerror(LOG_STDERR, gettext("Warning: failed to check the validity.\n")); } if (fullpath) free(fullpath); kmf_free_data(&cert); kmf_free_data(&cert_der); (void) kmf_finalize(kmfhandle); return (rv); }