-
- if (force || !*(context->control_key) || expired) {
- SHA_CTX sha1ctx;
- unsigned char sha1[20];
- int i = rand();
-
- SHA1_Init(&sha1ctx);
- SHA1_Update(&sha1ctx, &now, sizeof(now));
- SHA1_Update(&sha1ctx, &i, sizeof(i));
- SHA1_Final(sha1, &sha1ctx);
-
- context->control_timestamp = now;
- for (i = 0; i < 20; i++)
- sprintf(context->control_key + i * 2, "%02x", sha1[i]);
- snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
- FCGI_BeginJSON(context, STATUS_OK);
- FCGI_JSONPair("key", context->control_key);
- FCGI_EndJSON();
- } else {
- char buf[128];
- strftime(buf, 128, "%H:%M:%S %d-%m-%Y",
- localtime(&(context->control_timestamp)));
- FCGI_BeginJSON(context, STATUS_UNAUTHORIZED);
- FCGI_JSONPair("description", "Another user already has control");
- FCGI_JSONPair("current_user", context->control_ip);
- FCGI_JSONPair("when", buf);
- FCGI_EndJSON();
+ int i;
+
+ // Can't lock control if: User not actually logged in (sanity), or key is still valid and the user is not an admin
+ if (user_type == USER_UNAUTH ||
+ (user_type != USER_ADMIN && !expired && *(context->control_key) != '\0'))
+ return false;
+
+ // Release any existing control (if any)
+ FCGI_ReleaseControl(context);
+
+ // Set timestamp
+ context->control_timestamp = now;
+
+ // Generate a SHA1 hash for the user
+ SHA_CTX sha1ctx;
+ unsigned char sha1[20];
+ i = rand();
+ SHA1_Init(&sha1ctx);
+ SHA1_Update(&sha1ctx, &now, sizeof(now));
+ SHA1_Update(&sha1ctx, &i, sizeof(i));
+ SHA1_Final(sha1, &sha1ctx);
+ for (i = 0; i < sizeof(sha1); i++)
+ sprintf(context->control_key + i * 2, "%02x", sha1[i]);
+
+ // Set the IPv4 address
+ snprintf(context->control_ip, 16, "%s", getenv("REMOTE_ADDR"));
+
+ // Set the user name
+ int uname_len = strlen(user_name);
+ i = snprintf(context->user_name, sizeof(context->user_name), "%s", user_name);
+ if (i < uname_len) {
+ Log(LOGERR, "Username at %d characters too long (limit %d)",
+ uname_len, sizeof(context->user_name));
+ return false; // :-(