chat.c 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*
  2. * This file is part of the Mongoose project, http://code.google.com/p/mongoose
  3. * It implements an online chat server. For more details,
  4. * see the documentation on project page.
  5. * To start the server,
  6. * a) type "make" in the directory where this file lives
  7. * b) point your browser to http://127.0.0.1:8081
  8. *
  9. * NOTE(lsm): this file follows Google style, not BSD style as the rest of
  10. * Mongoose code.
  11. *
  12. * $Id: chat.c 513 2010-05-03 11:06:08Z valenok $
  13. */
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <assert.h>
  17. #include <string.h>
  18. #include <time.h>
  19. #include <pthread.h>
  20. #include "mongoose.h"
  21. #define MAX_USER_LEN 20
  22. #define MAX_MESSAGE_LEN 100
  23. #define MAX_MESSAGES 5
  24. #define MAX_SESSIONS 2
  25. static const char *login_url = "/login.html";
  26. static const char *authorize_url = "/authorize";
  27. static const char *web_root = "./html";
  28. static const char *http_ports = "8081,8082s";
  29. static const char *ssl_certificate = "ssl_cert.pem";
  30. static const char *ajax_reply_start =
  31. "HTTP/1.1 200 OK\r\n"
  32. "Cache: no-cache\r\n"
  33. "Content-Type: application/x-javascript\r\n"
  34. "\r\n";
  35. // Describes single message sent to a chat. If user is empty (0 length),
  36. // the message is then originated from the server itself.
  37. struct message {
  38. long id;
  39. char user[MAX_USER_LEN];
  40. char text[MAX_MESSAGE_LEN];
  41. time_t utc_timestamp;
  42. };
  43. // Describes web session.
  44. struct session {
  45. char session_id[33];
  46. char authenticated_user[MAX_USER_LEN];
  47. time_t expiration_timestamp_utc;
  48. };
  49. static struct message messages[MAX_MESSAGES]; // Ringbuffer for messages
  50. static struct session sessions[MAX_SESSIONS]; // Current sessions
  51. static long last_message_id;
  52. // Protects messages, sessions, last_message_id
  53. static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
  54. // Get a get of messages with IDs greater than last_id and transform them
  55. // into a JSON string. Return that string to the caller. The string is
  56. // dynamically allocated, caller must free it. If there are no messages,
  57. // NULL is returned.
  58. static char *messages_to_json(long last_id) {
  59. const struct message *message;
  60. int max_msgs, len;
  61. char buf[sizeof(messages)]; // Large enough to hold all messages
  62. // Read-lock the ringbuffer. Loop over all messages, making a JSON string.
  63. pthread_rwlock_rdlock(&rwlock);
  64. len = 0;
  65. max_msgs = sizeof(messages) / sizeof(messages[0]);
  66. // If client is too far behind, return all messages.
  67. if (last_message_id - last_id > max_msgs) {
  68. last_id = last_message_id - max_msgs;
  69. }
  70. for (; last_id < last_message_id; last_id++) {
  71. message = &messages[last_id % max_msgs];
  72. if (message->utc_timestamp == 0) {
  73. break;
  74. }
  75. // buf is allocated on stack and hopefully is large enough to hold all
  76. // messages (it may be too small if the ringbuffer is full and all
  77. // messages are large. in this case asserts will trigger).
  78. len += snprintf(buf + len, sizeof(buf) - len,
  79. "{user: '%s', text: '%s', timestamp: %lu, id: %lu},",
  80. message->user, message->text, message->utc_timestamp, message->id);
  81. assert(len > 0);
  82. assert((size_t) len < sizeof(buf));
  83. }
  84. pthread_rwlock_unlock(&rwlock);
  85. return len == 0 ? NULL : strdup(buf);
  86. }
  87. // If "callback" param is present in query string, this is JSONP call.
  88. // Return 1 in this case, or 0 if "callback" is not specified.
  89. // Wrap an output in Javascript function call.
  90. static int handle_jsonp(struct mg_connection *conn,
  91. const struct mg_request_info *request_info) {
  92. char cb[64];
  93. mg_get_qsvar(request_info, "callback", cb, sizeof(cb));
  94. if (cb[0] != '\0') {
  95. mg_printf(conn, "%s(", cb);
  96. }
  97. return cb[0] == '\0' ? 0 : 1;
  98. }
  99. // A handler for the /ajax/get_messages endpoint.
  100. // Return a list of messages with ID greater than requested.
  101. static void ajax_get_messages(struct mg_connection *conn,
  102. const struct mg_request_info *request_info) {
  103. char last_id[32], *json;
  104. int is_jsonp;
  105. mg_printf(conn, "%s", ajax_reply_start);
  106. is_jsonp = handle_jsonp(conn, request_info);
  107. mg_get_qsvar(request_info, "last_id", last_id, sizeof(last_id));
  108. if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) {
  109. mg_printf(conn, "[%s]", json);
  110. free(json);
  111. }
  112. if (is_jsonp) {
  113. mg_printf(conn, "%s", ")");
  114. }
  115. }
  116. // A handler for the /ajax/send_message endpoint.
  117. static void ajax_send_message(struct mg_connection *conn,
  118. const struct mg_request_info *request_info) {
  119. struct message *message;
  120. char text[sizeof(message->text) - 1];
  121. int is_jsonp;
  122. mg_printf(conn, "%s", ajax_reply_start);
  123. is_jsonp = handle_jsonp(conn, request_info);
  124. (void) mg_get_qsvar(request_info, "text", text, sizeof(text));
  125. if (text[0] != '\0') {
  126. // We have a message to store. Write-lock the ringbuffer,
  127. // grab the next message and copy data into it.
  128. pthread_rwlock_wrlock(&rwlock);
  129. message = &messages[last_message_id %
  130. (sizeof(messages) / sizeof(messages[0]))];
  131. // TODO(lsm): JSON-encode all text strings
  132. strncpy(message->text, text, sizeof(text));
  133. strncpy(message->user, "joe", sizeof(message->user));
  134. message->utc_timestamp = time(0);
  135. message->id = last_message_id++;
  136. pthread_rwlock_unlock(&rwlock);
  137. }
  138. mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true");
  139. if (is_jsonp) {
  140. mg_printf(conn, "%s", ")");
  141. }
  142. }
  143. // Redirect user to the login form. In the cookie, store the original URL
  144. // we came from, so that after the authorization we could redirect back.
  145. static void redirect_to_login(struct mg_connection *conn,
  146. const struct mg_request_info *request_info) {
  147. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  148. "Set-Cookie: original_url=%s\r\n"
  149. "Location: %s\r\n\r\n", request_info->uri, login_url);
  150. }
  151. // Return 1 if username/password is allowed, 0 otherwise.
  152. static int check_password(const char *user, const char *password) {
  153. // In production environment we should ask an authentication system
  154. // to authenticate the user.
  155. // Here however we do trivial check: if username == password, allow.
  156. return (strcmp(user, password) == 0 ? 1 : 0);
  157. }
  158. // A handler for the /authorize endpoint.
  159. // Login page form sends user name and password to this endpoint.
  160. static void authorize(struct mg_connection *conn,
  161. const struct mg_request_info *request_info) {
  162. char user[20], password[20], original_url[200];
  163. // Fetch user name and password.
  164. mg_get_qsvar(request_info, "user", user, sizeof(user));
  165. mg_get_qsvar(request_info, "password", password, sizeof(password));
  166. mg_get_cookie(conn, "original_url", original_url, sizeof(original_url));
  167. if (user[0] && password[0] && check_password(user, password)) {
  168. // Authentication success:
  169. // 1. create new session
  170. // 2. set session ID token in the cookie
  171. // 3. remove original_url from the cookie - not needed anymore
  172. // 4. redirect client back to the original URL
  173. // TODO(lsm): implement sessions.
  174. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  175. "Set-Cookie: sid=1234; max-age=2h; http-only\r\n" // Set session ID
  176. "Set-Cookie: original_url=/; max_age=0\r\n" // Delete original_url
  177. "Location: %s\r\n\r\n", original_url[0] == '\0' ? "/" : original_url);
  178. } else {
  179. // Authentication failure, redirect to login again.
  180. redirect_to_login(conn, request_info);
  181. }
  182. }
  183. // Return 1 if request is authorized, 0 otherwise.
  184. static int is_authorized(const struct mg_connection *conn,
  185. const struct mg_request_info *request_info) {
  186. // TODO(lsm): implement this part: fetch session ID from the cookie.
  187. return 0;
  188. }
  189. // Return 1 if authorization is required for requested URL, 0 otherwise.
  190. static int must_authorize(const struct mg_request_info *request_info) {
  191. return (strcmp(request_info->uri, login_url) != 0 &&
  192. strcmp(request_info->uri, authorize_url) != 0);
  193. }
  194. static enum mg_error_t process_request(struct mg_connection *conn,
  195. const struct mg_request_info *request_info) {
  196. enum mg_error_t processed = MG_SUCCESS;
  197. if (must_authorize(request_info) &&
  198. !is_authorized(conn, request_info)) {
  199. // If user is not authorized, redirect to the login form.
  200. redirect_to_login(conn, request_info);
  201. } else if (strcmp(request_info->uri, authorize_url) == 0) {
  202. authorize(conn, request_info);
  203. } else if (strcmp(request_info->uri, "/ajax/get_messages") == 0) {
  204. ajax_get_messages(conn, request_info);
  205. } else if (strcmp(request_info->uri, "/ajax/send_message") == 0) {
  206. ajax_send_message(conn, request_info);
  207. } else {
  208. // No suitable handler found, mark as not processed. Mongoose will
  209. // try to serve the request.
  210. processed = MG_ERROR;
  211. }
  212. return processed;
  213. }
  214. int main(int argc, char *argv[]) {
  215. struct mg_context *ctx;
  216. ctx = mg_start();
  217. mg_set_option(ctx, "root", web_root);
  218. mg_set_option(ctx, "ssl_cert", ssl_certificate); // Must be set before ports
  219. mg_set_option(ctx, "ports", http_ports);
  220. mg_set_option(ctx, "dir_list", "no"); // Disable directory listing
  221. mg_set_callback(ctx, MG_EVENT_NEW_REQUEST, &process_request);
  222. printf("Chat server started on ports %s, press enter to quit.\n", http_ports);
  223. getchar();
  224. mg_stop(ctx);
  225. printf("%s\n", "Chat server stopped.");
  226. return EXIT_SUCCESS;
  227. }
  228. // vim:ts=2:sw=2:et