Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include <iostream>
- //#include "base64.h"
- //#include "xmlParser.h"
- //
- //using namespace std;
- //
- //int main() {
- // cout << base64_decode("dGVzdDp0ZXN0") << "\n";
- // system("sleep 1");
- //}
- /***** inetserver.cpp *****/
- #include <iostream>
- #include <sstream>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h> /* for getenv */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h> /* Internet domain header */
- #include <ctype.h>
- #include <mysql.h>
- #include <mysql++/mysql++.h>
- //#include <result.h>
- //#include "xmlParse.h"
- #include "base64.h"
- #define SERVER_PORT 32650
- #define Debug 1
- using namespace std;
- using namespace mysqlpp;
- template <class T>
- inline std::string to_string (const T& t) {
- std::stringstream ss;
- ss << t;
- return ss.str();
- }
- void pingdb(Connection&); //fw declaration for connectdb
- void connectdb(Connection& conn) {
- // connect to mysql
- // mysqlpp::Connection(const char *db, coregex.hnst char *server=0, const char *user=0, const char *password=0, unsigned int port=0)
- try {
- conn.connect("skalin01", "pdc-amd01.poly.edu", "skalin01", "p0344698");
- } catch(Exception& e) {
- // probably wrong db parameter, fail gracefully here.
- // clean up, then
- cerr << "Connection to DB interrupted - trying to reconnect\n";
- pingdb(conn);
- }
- }
- void pingdb(Connection& conn) {
- // check connection & reconnect if disconnected
- // conn.ping() returns a bool.
- // retry until connectted again.
- while(!conn.ping()) {
- sleep(10);
- connectdb(conn);
- }
- }
- bool is_numeric(const char *p) {
- if (*p) {
- char c;
- while ((c=*p++)) {
- if (!isdigit(c)) return 0;
- }
- return true;
- }
- return false;
- }
- struct sockaddr_in self = {AF_INET,
- 0
- };
- int main() {
- // connect to mysql
- // mysqlpp::Connection(const char *db, const char *server=0, const char *user=0, const char *password=0, unsigned int port=0)
- mysqlpp::Connection conn(true);
- try {
- conn.connect("skalin01", "pdc-amd01.poly.edu", "skalin01", "p0344698");
- } catch(Exception& e) {
- // probably wrong db parameter, fail gracefully here.
- // clean up, then
- cerr << "Could not connect to DB to begin with!\nExiting.\n";
- exit(1);
- }
- int soc, ns, k;
- char buf[1024];
- struct sockaddr_in peer = {AF_INET};
- self.sin_port = htons(SERVER_PORT);
- socklen_t peer_len = sizeof(peer);
- int val;
- /* set up listening socket soc */
- soc = socket(AF_INET, SOCK_STREAM, 0);
- if (soc < 0) {
- perror("server:socket");
- exit(1);
- }
- val = 1;
- if (setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &val, sizeof val) != 0) {
- perror("server:setsockopt");
- exit(1);
- }
- if (bind(soc, (struct sockaddr *)&self, sizeof(self)) == -1) {
- perror("server:bind");
- close(soc);
- exit(1);
- }
- listen(soc, 1);
- /* accept connection request */
- ns = accept(soc, (struct sockaddr *)&peer, &peer_len);
- if (ns < 0) {
- perror("server:accept");
- close(soc);
- exit(1);
- }
- /* data transfer on connected socket ns */
- k = read(ns, buf, sizeof(buf) - 1);
- buf[k] = '\0'; /* null-terminate string */
- //debug
- //printf("SERVER RECEIVED: %s\n",buf);
- string buffer(buf);
- int request_url_begin(buffer.find_first_of("T ")+2), request_url_end(buffer.find(" HTTP/1.1"));
- //initialize request url
- string request_url(buffer.substr(request_url_begin, request_url_end-request_url_begin));
- int page_begin(request_url.find_last_of("/")+1), page_end(request_url.find(".xml"));
- string page_requested(request_url.substr(page_begin, page_end-page_begin));
- string action_url(request_url.substr(0, page_begin-1));
- int action_begin(action_url.find_last_of("/")+1), action_end(action_url.size());
- string action(action_url.substr(action_begin, action_end-action_begin));
- /*
- now, --action-- is the directory the xml file resides in, and
- --page_requsted-- is the xml file
- */
- string replyToClient; //this is what we will send back
- //here come the if/else
- if (page_requested == "register") {
- //register the user here
- int regline_begin(buffer.find("screen_name=")), regline_end(buffer.find_last_of("\r"));
- string regline(buffer.substr(regline_begin, regline_end-regline_begin));
- int screen_name_begin(regline.find_first_of("screen_name=")+12), screen_name_end(regline.find_first_of("&"));
- string screen_name(regline.substr(screen_name_begin, screen_name_end-screen_name_begin));
- int password_begin(regline.find("password=")+9), password_end(regline.size());
- string password(regline.substr(password_begin, password_end-password_begin));
- #ifdef Debug
- cout << "\nregline = " << regline << "\nscreen_name = " << screen_name << "; password = " << password << "\n";
- #endif
- //MYSQL request here
- //check if user exists
- string sql("SELECT name FROM user WHERE name='" + screen_name + "'");
- Query query = conn.query(sql);
- #ifdef Debug
- cout << "\n\n\n"<< query << endl;
- #endif
- StoreQueryResult checkuser = query.store();
- #ifdef Debug
- cout << "numrows = " << checkuser << endl;
- #endif
- int username_exist = checkuser.num_rows();
- if(username_exist > 0) {
- //echo "The username you specified has already been taken. Please try again:\n\n";
- //send error 403 to client, username taken
- replyToClient = "HTTP/1.1 403 Forbidden\n";
- replyToClient += "Content-Type: application/xml; charset=utf-8\n";
- replyToClient += "Connection: close\r\n\r\n";
- replyToClient += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
- replyToClient += "<hash>\n<request>";
- replyToClient += request_url;
- replyToClient += "</request>\n<error>The username you specified has already been taken.</error>\n</hash>\r\n\r\n";
- //send reply
- //debug
- cout << replyToClient;
- } else {
- sql = "SELECT MAX(id) FROM user";
- Query query = conn.query(sql);
- UseQueryResult res = query.use();
- Row row = res.fetch_row();
- #ifdef Debug
- cout << "\nCurrent max id: " << row["MAX(id)"] << "\n";
- #endif
- int next_id = row["MAX(id)"];
- next_id++;
- #ifdef Debug
- cout << "\nNext id: " << next_id << "\n";
- #endif
- sql = "INSERT INTO user(id, name, password) VALUES('"+to_string(next_id)+"', '"+screen_name+"', SHA1('"+password+"'))";
- #ifdef Debug
- cout << "\nQuery: " << sql << endl;
- #endif
- while (query.more_results()) {
- query.store_next();
- }
- query = conn.query(sql);
- if(!query.exec()) {
- std::cerr << "Failed adding a user.\n" << std::endl;
- }
- replyToClient = "HTTP/1.1 201 Created\n";
- replyToClient += "Content-Type: application/xml; charset=utf-8\n";
- replyToClient += "Connection: close\r\n\r\n";
- replyToClient += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
- replyToClient += "<user>\n<id>";
- replyToClient += to_string(next_id);
- replyToClient += "</id>\n<screen_name>";
- replyToClient += screen_name;
- replyToClient += "</screen_name>\n</user>\r\n\r\n";
- //send reply
- //debug
- cout << replyToClient;
- }
- } else if (action == "create") {
- //follow the friend
- if (is_numeric(page_requested.c_str())) {
- //it's a userid
- //MYSQL request here
- } else {
- //it's a username
- //MYSQL request here
- }
- } else if (action == "statuses") {
- if (page_requested == "followers") {
- //show all the tweets of the user
- int cursor_begin(request_url.find("cursor=")+7), cursor_end(request_url.size());
- string cursor_str(request_url.substr(cursor_begin, cursor_end-cursor_begin));
- int cursor(atoi(cursor_str.c_str()));
- //MYSQL request here
- std::string sql = "SELECT id, name FROM user WHERE id = 1";
- mysqlpp::Query query = conn.query(sql);
- // this is mysqlpp version 3
- if(mysqlpp::UseQueryResult res = query.use()) {
- // fetch one row
- while(mysqlpp::Row row = res.fetch_row()) {
- std::cout << "<user><user_id>" << row["id"] << "</user_id>"
- << "<screen_name>" << row["name"] << "</screen_name></user>";
- }
- // Check for error: can't distinguish "end of results" and
- // error cases in return from fetch_row() otherwise.
- if(conn.errnum()) {
- std::cerr << "Error fetching a row: " << conn.error() << std::endl;
- }
- } else {
- std::cerr << "Failed to query SQL: " << sql << std::endl;
- }
- }
- } else if (action == "user_timeline") {
- //see all user's tweets
- int count(10);
- int count_begin(request_url.find("count=")+7), count_end(request_url.find("&"));
- string count_str(request_url.substr(count_begin, count_end-count_begin));
- if (!count_str.empty())
- count = (atoi(count_str.c_str())); //set count
- int since_id_begin(request_url.find("since_id=")+9), since_id_end(request_url.find("&"));
- string since_id_str(request_url.substr(since_id_begin, since_id_end-since_id_begin));
- int since_id(atoi(since_id_str.c_str()));
- int max_id_begin(request_url.find("max_id=")+7), max_id_end(request_url.find("&"));
- string max_id_str(request_url.substr(max_id_begin, max_id_end-max_id_begin));
- int max_id(atoi(max_id_str.c_str()));
- //by now, count, max_id and since_id are set
- if (is_numeric(page_requested.c_str())) {
- //it's a userid
- //MYSQL request here
- } else {
- //it's a username
- //MYSQL request here
- }
- } else if (action == "statuses") {
- if (page_requested == "update") {
- //post a tweet
- int statline_begin(buffer.find("status=")), statline_end(buffer.find_last_of("\r"));
- string statline(buffer.substr(statline_begin, statline_end-statline_begin));
- int status_begin(statline.find_first_of("status=")+12), status_end(statline.find_first_of("&"));
- string status(statline.substr(status_begin, status_end-status_begin));
- }
- } else {
- //can't understand what's going on, error 400
- }
- //debug
- #ifdef Debug
- cout << "url = " << request_url << "\n";
- cout << "action = " << action << "; page_requested = " << page_requested << "\n\n";
- #endif
- /*
- string get, login, host;
- int auth_begin(buffer.find("Basic ")+6), auth_end(buffer.find("Host")-2);
- string auth64(buffer.substr(auth_begin, auth_end-auth_begin));
- cout << "\n\n" << base64_decode(auth64) << endl;
- */
- /*replyToClient = "Testing testing 123321 wooooooooooooo.";
- for (int i=0;i<=replyToClient.size();i++)
- {
- buf[i]=replyToClient[i];
- }
- cout << buf;
- buf[sizeof(replyToClient)-1] = '\0';*/
- int write_return = write(ns, replyToClient.c_str(), replyToClient.size()-1);
- #ifdef Debug
- cout << "Write returned: " << write_return << endl;
- #endif
- //write(ns, buf, k);
- close(ns);
- close(soc);
- return(0);
- }
- /***** end of inetserver.c *****/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement