CDomainSocket.cc
Go to the documentation of this file.00001 #include "CDomainSocket.h"
00002 CDomainSocket::CDomainSocket():
00003 mIsInitialized(false){
00004 };
00005
00007 CDomainSocket::CDomainSocket(const string& inPath):
00008 mIsInitialized(false){
00009 this->listenToPath(inPath);
00010 };
00011
00013 CDomainSocket::~CDomainSocket(){
00014 if(mIsInitialized){
00015 close(mSocketDescriptor);
00016 }
00017 };
00019 bool CDomainSocket::listenToPath(const string& inPath){
00020 mPath=inPath;
00021
00022 if (( mSocketDescriptor= socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
00023 perror("socket");
00024 return false;
00025 }
00026
00027 mSocketStructure.sun_family = AF_UNIX;
00028
00029 cout << "Making socket for path " << mPath << endl;
00030 strcpy(mSocketStructure.sun_path, mPath.c_str());
00031 unlink(mSocketStructure.sun_path);
00032
00033 int len = strlen(mSocketStructure.sun_path) + sizeof(mSocketStructure.sun_family);
00034 if (bind(mSocketDescriptor, (struct sockaddr *)&mSocketStructure, len) == -1) {
00035 perror("bind");
00036 return 0;
00037 }
00038 if (listen(mSocketDescriptor, 5) == -1) {
00039 perror("listen");
00040 return 0;
00041 }
00042
00043 if(chmod(mPath.c_str(),
00044 S_IRUSR|S_IWUSR)){
00045 perror("chmod");
00046 return 0;
00047 }
00048 mIsInitialized=1;
00049 return 1;
00050 };
00052 CDomainSocket::operator bool()const{
00053 return mIsInitialized;
00054 }
00056 string CDomainSocket::getPath()const{
00057 return mPath;
00058 }
00060 void CDomainSocket::serveStream(int inSocket){
00061 int done = 0;
00062 char str[2];
00063 string lMessage;
00064 int lRead(0);
00065 do {
00066 lRead = recv(inSocket,
00067 str, 1, 0);
00068 if (lRead <= 0) {
00069 cerr << "here?" << endl;
00070 if (lRead < 0) perror("recv");
00071 done = 1;
00072 }else{
00073 str[lRead]=char(0);
00074 lMessage+=str;
00075 }
00076
00077 } while (!done);
00078
00079 cout << " after while" << endl;
00080
00081 if (send(inSocket, lMessage.c_str(), lMessage.size(), 0) < 0) {
00082 perror("send");
00083 }
00084 }
00085
00086 bool CDomainSocket::acceptAndServe(){
00087 struct sockaddr_un lAcceptedSocket;
00091 unsigned int t = sizeof(lAcceptedSocket);
00092 int s2(0);
00093 if ((s2 = accept(this->getSocketDescriptor(), (struct sockaddr *)&lAcceptedSocket, &t)) == -1) {
00094 perror("accept");
00095 return false;
00096 }
00097 {
00098 struct ucred lCredentials;
00099 socklen_t lSize = sizeof(lCredentials);
00100 if (getsockopt(s2,
00101 SOL_SOCKET,
00102 SO_PEERCRED,
00103 &lCredentials,
00104 &lSize)
00105 == 0){
00106
00107 cout << "Socket credentials:" << endl
00108 << "Process ID: " << lCredentials.pid << endl
00109 << "User ID: " << lCredentials.uid << endl
00110 << "Group ID: " << lCredentials.gid << endl;
00111 }
00112 }
00113 cout << "connected: " << this->getPath() << endl;
00114
00115 this->serveStream(s2);
00116
00117 return true;
00118 }