Skip to content

Instantly share code, notes, and snippets.

@unbit
Last active August 29, 2015 14:23
Show Gist options
  • Save unbit/4cc505555ec7fad0f7f7 to your computer and use it in GitHub Desktop.
Save unbit/4cc505555ec7fad0f7f7 to your computer and use it in GitHub Desktop.
uWSGI router_remoteuser plugin
#include <uwsgi.h>
/*
extract REMOTE_USER from Authorization header
[uwsgi]
plugin = router_remoteuser
route-run = remoteuser:
route-run = log:${REMOTE_USER}
...
*/
static int uwsgi_routing_func_remoteuser(struct wsgi_request *wsgi_req, struct uwsgi_route *ur) {
// skip if already authenticated
if (wsgi_req->remote_user_len > 0) {
goto end;
}
// check for valid Authorization header
if (wsgi_req->authorization_len > 7) {
if (strncmp(wsgi_req->authorization, "Basic ", 6))
goto end;
size_t auth_len = 0;
char *auth = uwsgi_base64_decode(wsgi_req->authorization+6, wsgi_req->authorization_len-6, &auth_len);
if (!auth) goto end;
// get the user part
char *colon = memchr(auth, ':', auth_len);
if (!colon) goto end;
wsgi_req->remote_user = uwsgi_req_append(wsgi_req, "REMOTE_USER", 11, auth, colon-auth);
// fix remote_user_len if the append has been sucessful
if (wsgi_req->remote_user) {
wsgi_req->remote_user_len = colon-auth;
}
free(auth);
}
end:
return UWSGI_ROUTE_NEXT;
}
static int uwsgi_router_remoteuser(struct uwsgi_route *ur, char *args) {
ur->func = uwsgi_routing_func_remoteuser;
return 0;
}
static void router_remoteuser_register(void) {
uwsgi_register_router("remoteuser", uwsgi_router_remoteuser);
}
extern struct uwsgi_server uwsgi;
static void router_remoteuser_harakiri(int wid) {
int i;
for(i=0;i<uwsgi.cores;i++) {
struct uwsgi_core *uc = &uwsgi.workers[wid].cores[i];
if (uc->in_request) {
uwsgi_log_verbose("REMOTE_USER for core %d on worker %d: %.*s\n", i, wid, uc->req.remote_user_len, uc->req.remote_user);
}
}
}
struct uwsgi_plugin router_remoteuser_plugin = {
.name = "router_remoteuser",
.on_load = router_remoteuser_register,
.harakiri = router_remoteuser_harakiri,
};
@unbit
Copy link
Author

unbit commented Jun 30, 2015

Build it with

uwsgi --build-plugin router_remoteuser.c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment