chat.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // This file is part of the Mongoose project, http://code.google.com/p/mongoose
  2. // It implements an online chat server. For more details,
  3. // see the documentation on the project web site.
  4. // To test the application,
  5. // 1. type "make" in the directory where this file lives
  6. // 2. point your browser to http://127.0.0.1:8081
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <assert.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include <stdarg.h>
  13. #include <pthread.h>
  14. #include "mongoose.h"
  15. #define MAX_USER_LEN 20
  16. #define MAX_MESSAGE_LEN 100
  17. #define MAX_MESSAGES 5
  18. #define MAX_SESSIONS 2
  19. #define SESSION_TTL 120
  20. static const char *authorize_url = "/authorize";
  21. static const char *login_url = "/login.html";
  22. static const char *ajax_reply_start =
  23. "HTTP/1.1 200 OK\r\n"
  24. "Cache: no-cache\r\n"
  25. "Content-Type: application/x-javascript\r\n"
  26. "\r\n";
  27. // Describes single message sent to a chat. If user is empty (0 length),
  28. // the message is then originated from the server itself.
  29. struct message {
  30. long id; // Message ID
  31. char user[MAX_USER_LEN]; // User that have sent the message
  32. char text[MAX_MESSAGE_LEN]; // Message text
  33. time_t timestamp; // Message timestamp, UTC
  34. };
  35. // Describes web session.
  36. struct session {
  37. char session_id[33]; // Session ID, must be unique
  38. char random[20]; // Random data used for extra user validation
  39. char user[MAX_USER_LEN]; // Authenticated user
  40. time_t expire; // Expiration timestamp, UTC
  41. };
  42. static struct message messages[MAX_MESSAGES]; // Ringbuffer for messages
  43. static struct session sessions[MAX_SESSIONS]; // Current sessions
  44. static long last_message_id;
  45. // Protects messages, sessions, last_message_id
  46. static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
  47. // Get session object for the connection. Caller must hold the lock.
  48. static struct session *get_session(const struct mg_connection *conn) {
  49. int i;
  50. char session_id[33];
  51. time_t now = time(NULL);
  52. mg_get_cookie(conn, "session", session_id, sizeof(session_id));
  53. for (i = 0; i < MAX_SESSIONS; i++) {
  54. if (sessions[i].expire != 0 &&
  55. sessions[i].expire > now &&
  56. strcmp(sessions[i].session_id, session_id) == 0) {
  57. break;
  58. }
  59. }
  60. return i == MAX_SESSIONS ? NULL : &sessions[i];
  61. }
  62. static void get_qsvar(const struct mg_request_info *request_info,
  63. const char *name, char *dst, size_t dst_len) {
  64. const char *qs = request_info->query_string;
  65. mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);
  66. }
  67. // Get a get of messages with IDs greater than last_id and transform them
  68. // into a JSON string. Return that string to the caller. The string is
  69. // dynamically allocated, caller must free it. If there are no messages,
  70. // NULL is returned.
  71. static char *messages_to_json(long last_id) {
  72. const struct message *message;
  73. int max_msgs, len;
  74. char buf[sizeof(messages)]; // Large enough to hold all messages
  75. // Read-lock the ringbuffer. Loop over all messages, making a JSON string.
  76. pthread_rwlock_rdlock(&rwlock);
  77. len = 0;
  78. max_msgs = sizeof(messages) / sizeof(messages[0]);
  79. // If client is too far behind, return all messages.
  80. if (last_message_id - last_id > max_msgs) {
  81. last_id = last_message_id - max_msgs;
  82. }
  83. for (; last_id < last_message_id; last_id++) {
  84. message = &messages[last_id % max_msgs];
  85. if (message->timestamp == 0) {
  86. break;
  87. }
  88. // buf is allocated on stack and hopefully is large enough to hold all
  89. // messages (it may be too small if the ringbuffer is full and all
  90. // messages are large. in this case asserts will trigger).
  91. len += snprintf(buf + len, sizeof(buf) - len,
  92. "{user: '%s', text: '%s', timestamp: %lu, id: %lu},",
  93. message->user, message->text, message->timestamp, message->id);
  94. assert(len > 0);
  95. assert((size_t) len < sizeof(buf));
  96. }
  97. pthread_rwlock_unlock(&rwlock);
  98. return len == 0 ? NULL : strdup(buf);
  99. }
  100. // If "callback" param is present in query string, this is JSONP call.
  101. // Return 1 in this case, or 0 if "callback" is not specified.
  102. // Wrap an output in Javascript function call.
  103. static int handle_jsonp(struct mg_connection *conn,
  104. const struct mg_request_info *request_info) {
  105. char cb[64];
  106. get_qsvar(request_info, "callback", cb, sizeof(cb));
  107. if (cb[0] != '\0') {
  108. mg_printf(conn, "%s(", cb);
  109. }
  110. return cb[0] == '\0' ? 0 : 1;
  111. }
  112. // A handler for the /ajax/get_messages endpoint.
  113. // Return a list of messages with ID greater than requested.
  114. static void ajax_get_messages(struct mg_connection *conn,
  115. const struct mg_request_info *request_info) {
  116. char last_id[32], *json;
  117. int is_jsonp;
  118. mg_printf(conn, "%s", ajax_reply_start);
  119. is_jsonp = handle_jsonp(conn, request_info);
  120. get_qsvar(request_info, "last_id", last_id, sizeof(last_id));
  121. if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) {
  122. mg_printf(conn, "[%s]", json);
  123. free(json);
  124. }
  125. if (is_jsonp) {
  126. mg_printf(conn, "%s", ")");
  127. }
  128. }
  129. // Allocate new message. Caller must hold the lock.
  130. static struct message *new_message(void) {
  131. static int size = sizeof(messages) / sizeof(messages[0]);
  132. struct message *message = &messages[last_message_id % size];
  133. message->id = last_message_id++;
  134. message->timestamp = time(0);
  135. return message;
  136. }
  137. static void my_strlcpy(char *dst, const char *src, size_t len) {
  138. strncpy(dst, src, len);
  139. dst[len - 1] = '\0';
  140. }
  141. // A handler for the /ajax/send_message endpoint.
  142. static void ajax_send_message(struct mg_connection *conn,
  143. const struct mg_request_info *request_info) {
  144. struct message *message;
  145. struct session *session;
  146. char text[sizeof(message->text) - 1];
  147. int is_jsonp;
  148. mg_printf(conn, "%s", ajax_reply_start);
  149. is_jsonp = handle_jsonp(conn, request_info);
  150. get_qsvar(request_info, "text", text, sizeof(text));
  151. if (text[0] != '\0') {
  152. // We have a message to store. Write-lock the ringbuffer,
  153. // grab the next message and copy data into it.
  154. pthread_rwlock_wrlock(&rwlock);
  155. message = new_message();
  156. // TODO(lsm): JSON-encode all text strings
  157. session = get_session(conn);
  158. assert(session != NULL);
  159. my_strlcpy(message->text, text, sizeof(text));
  160. my_strlcpy(message->user, session->user, sizeof(message->user));
  161. pthread_rwlock_unlock(&rwlock);
  162. }
  163. mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true");
  164. if (is_jsonp) {
  165. mg_printf(conn, "%s", ")");
  166. }
  167. }
  168. // Redirect user to the login form. In the cookie, store the original URL
  169. // we came from, so that after the authorization we could redirect back.
  170. static void redirect_to_login(struct mg_connection *conn,
  171. const struct mg_request_info *request_info) {
  172. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  173. "Set-Cookie: original_url=%s\r\n"
  174. "Location: %s\r\n\r\n",
  175. request_info->uri, login_url);
  176. }
  177. // Return 1 if username/password is allowed, 0 otherwise.
  178. static int check_password(const char *user, const char *password) {
  179. // In production environment we should ask an authentication system
  180. // to authenticate the user.
  181. // Here however we do trivial check that user and password are not empty
  182. return (user[0] && password[0]);
  183. }
  184. // Allocate new session object
  185. static struct session *new_session(void) {
  186. int i;
  187. time_t now = time(NULL);
  188. pthread_rwlock_wrlock(&rwlock);
  189. for (i = 0; i < MAX_SESSIONS; i++) {
  190. if (sessions[i].expire == 0 || sessions[i].expire < now) {
  191. sessions[i].expire = time(0) + SESSION_TTL;
  192. break;
  193. }
  194. }
  195. pthread_rwlock_unlock(&rwlock);
  196. return i == MAX_SESSIONS ? NULL : &sessions[i];
  197. }
  198. // Generate session ID. buf must be 33 bytes in size.
  199. // Note that it is easy to steal session cookies by sniffing traffic.
  200. // This is why all communication must be SSL-ed.
  201. static void generate_session_id(char *buf, const char *random,
  202. const char *user) {
  203. mg_md5(buf, random, user, NULL);
  204. }
  205. static void send_server_message(const char *fmt, ...) {
  206. va_list ap;
  207. struct message *message;
  208. pthread_rwlock_wrlock(&rwlock);
  209. message = new_message();
  210. message->user[0] = '\0'; // Empty user indicates server message
  211. va_start(ap, fmt);
  212. vsnprintf(message->text, sizeof(message->text), fmt, ap);
  213. va_end(ap);
  214. pthread_rwlock_unlock(&rwlock);
  215. }
  216. // A handler for the /authorize endpoint.
  217. // Login page form sends user name and password to this endpoint.
  218. static void authorize(struct mg_connection *conn,
  219. const struct mg_request_info *request_info) {
  220. char user[MAX_USER_LEN], password[MAX_USER_LEN];
  221. struct session *session;
  222. // Fetch user name and password.
  223. get_qsvar(request_info, "user", user, sizeof(user));
  224. get_qsvar(request_info, "password", password, sizeof(password));
  225. if (check_password(user, password) && (session = new_session()) != NULL) {
  226. // Authentication success:
  227. // 1. create new session
  228. // 2. set session ID token in the cookie
  229. // 3. remove original_url from the cookie - not needed anymore
  230. // 4. redirect client back to the original URL
  231. //
  232. // The most secure way is to stay HTTPS all the time. However, just to
  233. // show the technique, we redirect to HTTP after the successful
  234. // authentication. The danger of doing this is that session cookie can
  235. // be stolen and an attacker may impersonate the user.
  236. // Secure application must use HTTPS all the time.
  237. my_strlcpy(session->user, user, sizeof(session->user));
  238. snprintf(session->random, sizeof(session->random), "%d", rand());
  239. generate_session_id(session->session_id, session->random, session->user);
  240. send_server_message("<%s> joined", session->user);
  241. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  242. "Set-Cookie: session=%s; max-age=3600; http-only\r\n" // Session ID
  243. "Set-Cookie: user=%s\r\n" // Set user, needed by Javascript code
  244. "Set-Cookie: original_url=/; max-age=0\r\n" // Delete original_url
  245. "Location: /\r\n\r\n",
  246. session->session_id, session->user);
  247. } else {
  248. // Authentication failure, redirect to login.
  249. redirect_to_login(conn, request_info);
  250. }
  251. }
  252. // Return 1 if request is authorized, 0 otherwise.
  253. static int is_authorized(const struct mg_connection *conn,
  254. const struct mg_request_info *request_info) {
  255. struct session *session;
  256. char valid_id[33];
  257. int authorized = 0;
  258. // Always authorize accesses to login page and to authorize URI
  259. if (!strcmp(request_info->uri, login_url) ||
  260. !strcmp(request_info->uri, authorize_url)) {
  261. return 1;
  262. }
  263. pthread_rwlock_rdlock(&rwlock);
  264. if ((session = get_session(conn)) != NULL) {
  265. generate_session_id(valid_id, session->random, session->user);
  266. if (strcmp(valid_id, session->session_id) == 0) {
  267. session->expire = time(0) + SESSION_TTL;
  268. authorized = 1;
  269. }
  270. }
  271. pthread_rwlock_unlock(&rwlock);
  272. return authorized;
  273. }
  274. static void redirect_to_ssl(struct mg_connection *conn,
  275. const struct mg_request_info *request_info) {
  276. const char *p, *host = mg_get_header(conn, "Host");
  277. if (host != NULL && (p = strchr(host, ':')) != NULL) {
  278. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  279. "Location: https://%.*s:8082/%s:8082\r\n\r\n",
  280. (int) (p - host), host, request_info->uri);
  281. } else {
  282. mg_printf(conn, "%s", "HTTP/1.1 500 Error\r\n\r\nHost: header is not set");
  283. }
  284. }
  285. static int begin_request_handler(struct mg_connection *conn) {
  286. const struct mg_request_info *request_info = mg_get_request_info(conn);
  287. int processed = 1;
  288. if (!request_info->is_ssl) {
  289. redirect_to_ssl(conn, request_info);
  290. } else if (!is_authorized(conn, request_info)) {
  291. redirect_to_login(conn, request_info);
  292. } else if (strcmp(request_info->uri, authorize_url) == 0) {
  293. authorize(conn, request_info);
  294. } else if (strcmp(request_info->uri, "/ajax/get_messages") == 0) {
  295. ajax_get_messages(conn, request_info);
  296. } else if (strcmp(request_info->uri, "/ajax/send_message") == 0) {
  297. ajax_send_message(conn, request_info);
  298. } else {
  299. // No suitable handler found, mark as not processed. Mongoose will
  300. // try to serve the request.
  301. processed = 0;
  302. }
  303. return processed;
  304. }
  305. static const char *options[] = {
  306. "document_root", "html",
  307. "listening_ports", "8081,8082s",
  308. "ssl_certificate", "ssl_cert.pem",
  309. "num_threads", "5",
  310. NULL
  311. };
  312. int main(void) {
  313. struct mg_callbacks callbacks;
  314. struct mg_context *ctx;
  315. // Initialize random number generator. It will be used later on for
  316. // the session identifier creation.
  317. srand((unsigned) time(0));
  318. // Setup and start Mongoose
  319. memset(&callbacks, 0, sizeof(callbacks));
  320. callbacks.begin_request = begin_request_handler;
  321. if ((ctx = mg_start(&callbacks, NULL, options)) == NULL) {
  322. printf("%s\n", "Cannot start chat server, fatal exit");
  323. exit(EXIT_FAILURE);
  324. }
  325. // Wait until enter is pressed, then exit
  326. printf("Chat server started on ports %s, press enter to quit.\n",
  327. mg_get_option(ctx, "listening_ports"));
  328. getchar();
  329. mg_stop(ctx);
  330. printf("%s\n", "Chat server stopped.");
  331. return EXIT_SUCCESS;
  332. }
  333. // vim:ts=2:sw=2:et