From 119ac79bebd5c7a5401093671eba416c15a72ac1 Mon Sep 17 00:00:00 2001 From: Thomas Kolb Date: Wed, 21 Aug 2013 16:07:05 +0200 Subject: [PATCH] =?UTF-8?q?Show=20client=E2=80=99s=20ip=20address=20in=20l?= =?UTF-8?q?og?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/main.h | 4 ++++ src/main.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/include/main.h b/include/main.h index d6303e4..cef5dfa 100644 --- a/include/main.h +++ b/include/main.h @@ -3,6 +3,8 @@ #include +#define IPSTR_MAXLEN 47 + enum ResultCode { RC_OK = 0, // No problem (so far) RC_EXISTS = 1, // On upload, the file to be uploaded already existed @@ -26,6 +28,8 @@ struct ConnectionState { FILE *upload_fd; char uploadFilename[PATH_MAX]; + char clientIP[IPSTR_MAXLEN]; + enum ResultCode result; enum RequestType requestType; diff --git a/src/main.c b/src/main.c index a12189f..fda3934 100644 --- a/src/main.c +++ b/src/main.c @@ -78,6 +78,48 @@ void request_completed(void *cls, free(connstate); } +void get_client_ip_from_connection(struct MHD_Connection *connection, + struct ConnectionState *connstate) { + struct sockaddr **ci = + (struct sockaddr **)MHD_get_connection_info( + connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS); + + if(!ci) { + LOG(LVL_ERR, "Could not determine client address."); + return; + } + + struct sockaddr *sa = *ci; + + // convert ip address and extract port + uint16_t port = 0; + switch(sa->sa_family) { + case AF_INET: + inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), connstate->clientIP, IPSTR_MAXLEN); + + port = ntohs(((struct sockaddr_in*)sa)->sin_port); + break; + + case AF_INET6: + strcpy(connstate->clientIP, "["); + inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), connstate->clientIP+1, IPSTR_MAXLEN-1); + strcat(connstate->clientIP, "]"); + + port = ntohs(((struct sockaddr_in6*)sa)->sin6_port); + break; + + default: + LOG(LVL_ERR, "Address family is invalid: %i.", sa->sa_family); + return; + }; + + strcat(connstate->clientIP, ":"); + + int offset = strlen(connstate->clientIP); + + sprintf(connstate->clientIP + offset, "%u", port); +} + int parse_range(const char *range, off_t total_len, struct RequestRange *result) { char *numstr; char *dashptr; @@ -404,8 +446,11 @@ static int connection_handler(void * cls, strncpy(connstate->cleanedURL, url, PATH_MAX); remove_trailing_slash(connstate->cleanedURL); - LOG(LVL_INFO, "%s %s (local: %s)", - method, url, connstate->localFileName); + // get the remote address as a string + get_client_ip_from_connection(connection, connstate); + + LOG(LVL_INFO, "%s - %s %s (local: %s)", + connstate->clientIP, method, url, connstate->localFileName); if (0 == strcmp(method, "GET") || 0 == strcmp(method, "HEAD")) { // process GET arguments