2 * Copyright (C) 2015 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 * You can also choose to distribute this program under the terms of
20 * the Unmodified Binary Distribution Licence (as given in the file
21 * COPYING.UBDL), provided that you have satisfied its requirements.
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
29 * Hyper Text Transfer Protocol (HTTP) Basic authentication
36 #include <ipxe/base64.h>
37 #include <ipxe/http.h>
39 /* Disambiguate the various error causes */
40 #define EACCES_USERNAME __einfo_error ( EINFO_EACCES_USERNAME )
41 #define EINFO_EACCES_USERNAME \
42 __einfo_uniqify ( EINFO_EACCES, 0x01, \
43 "No username available for Basic authentication" )
46 * Perform HTTP Basic authentication
48 * @v http HTTP transaction
49 * @ret rc Return status code
51 static int http_basic_authenticate ( struct http_transaction *http ) {
52 struct http_request_auth *req = &http->request.auth;
54 /* Record username and password */
55 if ( ! http->uri->user ) {
56 DBGC ( http, "HTTP %p has no username for Basic "
57 "authentication\n", http );
58 return -EACCES_USERNAME;
60 req->username = http->uri->user;
61 req->password = ( http->uri->password ? http->uri->password : "" );
67 * Construct HTTP "Authorization" header for Basic authentication
69 * @v http HTTP transaction
71 * @v len Length of buffer
72 * @ret len Length of header value, or negative error
74 static int http_format_basic_auth ( struct http_transaction *http,
75 char *buf, size_t len ) {
76 struct http_request_auth *req = &http->request.auth;
77 size_t user_pw_len = ( strlen ( req->username ) + 1 /* ":" */ +
78 strlen ( req->password ) );
79 char user_pw[ user_pw_len + 1 /* NUL */ ];
82 assert ( req->username != NULL );
83 assert ( req->password != NULL );
85 /* Construct "user:password" string */
86 snprintf ( user_pw, sizeof ( user_pw ), "%s:%s",
87 req->username, req->password );
89 /* Construct response */
90 return base64_encode ( user_pw, user_pw_len, buf, len );
93 /** HTTP Basic authentication scheme */
94 struct http_authentication http_basic_auth __http_authentication = {
96 .authenticate = http_basic_authenticate,
97 .format = http_format_basic_auth,
100 /* Drag in HTTP authentication support */
101 REQUIRING_SYMBOL ( http_basic_auth );
102 REQUIRE_OBJECT ( httpauth );