chat.c 13 KB

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