Ejemplo n.º 1
0
void CWarMap::CheckWarEnd()
{
	if (m_bEnded)
		return;

	if (m_TeamData[0].iMemberCount == 0 || m_TeamData[1].iMemberCount == 0)
	{
		if (m_bTimeout)
			return;

		if (m_pkTimeoutEvent)
			return;

		Notice(LC_TEXT("길드전에 참가한 상대방 길드원이 아무도 없습니다."));
		Notice(LC_TEXT("1분 이내에 아무도 접속하지 않으면 길드전이 자동 종료됩니다."));

		sys_log(0, "CheckWarEnd: Timeout begin %u vs %u", m_TeamData[0].dwID, m_TeamData[1].dwID);

		war_map_info* info = AllocEventInfo<war_map_info>();
		info->pWarMap = this;

		SetTimeoutEvent(event_create(war_timeout_event, info, PASSES_PER_SEC(60)));
	}
	else
		CheckScore();
}
Ejemplo n.º 2
0
void GameEnd(unsigned char team)
{
	ShowLog();
	if (team == 'a')
		Notice("The Alliance of Free Systems (Team Red) is victorious!");
	else if (team == 'b')
		Notice("The Galactic Empire (Team Blue) is victorious!");
	
	game.playing = false;
}
Ejemplo n.º 3
0
static void
posplot_about (GtkWidget *menuitem) {
 Notice(
  "posplot/VOGL GUI driver\n"
  "(c) 1998-2007,2011-2014 by Bernd Feige, [email protected]\n"
  "Using the free GTK library: See http://www.gtk.org/"
 );
}
Ejemplo n.º 4
0
std::map<std::string,std::string> uhal::tests::default_arg_parsing ( int argc,char* argv[] )
{
    // Declare the supported options.
    po::options_description desc ( "Allowed options" );
    desc.add_options()
    ( "help,h", "produce help message" )
    ( "connection_file,c", po::value<std::string>()->default_value ( "", "Connection file URI" ) )
    ( "device_id,d", po::value<std::string>()->default_value ( "", "Device identifier" ) )
    ( "verbose,v", "Verbose output" )
    ( "very_verbose,V", "Very verbose output" )
    ;
    po::variables_map vm;

    try
    {
        po::store ( po::parse_command_line ( argc, argv, desc ), vm );
        po::notify ( vm );
    }
    catch ( std::exception& e )
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cout << "Usage: " << argv[0] << " [OPTIONS]" << std::endl;
        std::cout << desc << std::endl;
        exit ( 1 );
    }

    if ( vm.count ( "help" ) )
    {
        std::cout << "Usage: " << argv[0] << " [OPTIONS]" << std::endl;
        std::cout << desc << std::endl;
        exit ( 0 );
    }

    std::map<std::string,std::string> result;
    result["connection_file"] = vm["connection_file"].as<std::string>();
    result["device_id"] = vm["device_id"].as<std::string>();

    if ( vm.count ( "very_verbose" ) )
    {
        uhal::setLogLevelTo ( Debug() );
        result["very_verbose"] = "true";
        result["verbose"] = "true";
    }
    else if ( vm.count ( "verbose" ) )
    {
        uhal::setLogLevelTo ( Notice() );
        result["very_verbose"] = "false";
        result["verbose"] = "true";
    }
    else
    {
        uhal::setLogLevelTo ( Fatal() );
        result["very_verbose"] = "false";
        result["verbose"] = "false";
    }

    return result;
}
Ejemplo n.º 5
0
static void signal_kill_pid(int dummy) {
   int _errno;
   _errno = errno;
   diag_in_handler = 1;
   Notice("SIGALRM while waiting for wo child process to die, killing it now");
   Kill(socat_kill_pid, SIGTERM);
   diag_in_handler = 0;
   errno = _errno;
}
Ejemplo n.º 6
0
    Shape *MakeLoop(BlockSet &Blocks, BlockSet& Entries, BlockSet &NextEntries) {
      // Find the inner blocks in this loop. Proceed backwards from the entries until
      // you reach a seen block, collecting as you go.
      BlockSet InnerBlocks;
      BlockSet Queue = Entries;
      while (Queue.size() > 0) {
        Block *Curr = *(Queue.begin());
        Queue.erase(Queue.begin());
        if (InnerBlocks.find(Curr) == InnerBlocks.end()) {
          // This element is new, mark it as inner and remove from outer
          InnerBlocks.insert(Curr);
          Blocks.erase(Curr);
          // Add the elements prior to it
          for (BlockBranchMap::iterator iter = Curr->BranchesIn.begin(); iter != Curr->BranchesIn.end(); iter++) {
            Queue.insert(iter->first);
          }
        }
      }
      assert(InnerBlocks.size() > 0);

      for (BlockSet::iterator iter = InnerBlocks.begin(); iter != InnerBlocks.end(); iter++) {
        Block *Curr = *iter;
        for (BlockBranchMap::iterator iter = Curr->BranchesOut.begin(); iter != Curr->BranchesOut.end(); iter++) {
          Block *Possible = iter->first;
          if (InnerBlocks.find(Possible) == InnerBlocks.end() &&
              NextEntries.find(Possible) == NextEntries.find(Possible)) {
            NextEntries.insert(Possible);
          }
        }
      }

      PrintDebug("creating loop block:\n");
      DebugDump(InnerBlocks, "  inner blocks:");
      DebugDump(Entries, "  inner entries:");
      DebugDump(Blocks, "  outer blocks:");
      DebugDump(NextEntries, "  outer entries:");

      // TODO: Optionally hoist additional blocks into the loop

      LoopShape *Loop = new LoopShape();
      Notice(Loop);

      // Solipsize the loop, replacing with break/continue and marking branches as Processed (will not affect later calculations)
      // A. Branches to the loop entries become a continue to this shape
      for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
        Solipsize(*iter, Branch::Continue, Loop, InnerBlocks);
      }
      // B. Branches to outside the loop (a next entry) become breaks on this shape
      for (BlockSet::iterator iter = NextEntries.begin(); iter != NextEntries.end(); iter++) {
        Solipsize(*iter, Branch::Break, Loop, InnerBlocks);
      }
      // Finish up
      Shape *Inner = Process(InnerBlocks, Entries, NULL);
      Loop->Inner = Inner;
      return Loop;
    }
Ejemplo n.º 7
0
/* process an unnamed bidirectional "pipe" or "fifo" or "echo" argument with
   options */
static int xioopen_fifo_unnamed(xiofile_t *sock, struct opt *opts) {
   struct opt *opts2;
   int filedes[2];
   int numleft;
   int result;

   if (applyopts_single(&sock->stream, opts, PH_INIT) < 0)  return -1;
   applyopts(-1, opts, PH_INIT);

   if (Pipe(filedes) != 0) {
      Error2("pipe(%p): %s", filedes, strerror(errno));
      return -1;
   }
   /*0 Info2("pipe({%d,%d})", filedes[0], filedes[1]);*/

   sock->common.tag               = XIO_TAG_RDWR;
   sock->stream.dtype             = XIODATA_PIPE;
   sock->stream.fd                = filedes[0];
   sock->stream.para.bipipe.fdout = filedes[1];
   applyopts_cloexec(sock->stream.fd,                opts);
   applyopts_cloexec(sock->stream.para.bipipe.fdout, opts);

   /* one-time and input-direction options, no second application */
   retropt_bool(opts, OPT_IGNOREEOF, &sock->stream.ignoreeof);

   /* here we copy opts! */
   if ((opts2 = copyopts(opts, GROUP_FIFO)) == NULL) {
      return STAT_NORETRY;
   }

   /* apply options to first FD */
   if ((result = applyopts(sock->stream.fd, opts, PH_ALL)) < 0) {
      return result;
   }
   if ((result = applyopts_single(&sock->stream, opts, PH_ALL)) < 0) {
      return result;
   }

   /* apply options to second FD */
   if ((result = applyopts(sock->stream.para.bipipe.fdout, opts2, PH_ALL)) < 0)
   {
      return result;
   }

   if ((numleft = leftopts(opts)) > 0) {
      Error1("%d option(s) could not be used", numleft);
      showleft(opts);
   }
   Notice("writing to and reading from unnamed pipe");
   return 0;
}
Ejemplo n.º 8
0
// 리스트에 새 클라이언트를 추가합니다.
Client* addClient(Client* newClient) {
    char buffer[256];
    char head[HEAD_SIZE], value[VALUE_SIZE];

    int n;

    if (newClient == 0) return 0;

    // 우선 클라이언트가 일반 클라이언트이지, shell 클라이언트인지를 알아냅니다.
    readMsg(newClient->socket, head, value);
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_CLIENT) ) {
        // 일반 client 모드면 싱글 링크드리스트에 추가합니다.
        newClient->nextClient = 0;
        if (front != 0)
            newClient->nextClient = front;
        // 그냥 맨 앞에 넣습니다. 순서는 중요하지 않습니다.
        front = newClient;
        newClient->isShell = false;

    } else
    if ( !strcmp(head, MODE) && !strcmp(value, MODE_SHELL) ) {
        // shell client 모드면 shell 모드로 접속한 다른 클라이언트가 없는지 확인합니다.
        if (shellClient != 0) {
            writeMsg(newClient->socket, ERR, "SHELL_DUP");
            exit(1);
        }

        // shell 클라이언트는 리스트에 넣지 않고 따로 관리합니다.
        shellClient = newClient;
        newClient->isShell = true;
    } else {
        // 알 수 없는 client 접속
        writeMsg(newClient->socket, ERR, PROTO_ERR);
        return 0;
    }

    // 클라이언트의 이름을 설정합니다.
    sprintf(buffer, "Client(%d)", clientCount);
    clientCount++;
    writeMsg(newClient->socket, SET_NAME, buffer);

    // 클라이언트 정보를 출력합니다.
    Notice("Client");
    printf("(%d) connected, IP: %s, Port: %d\n", clientCount, newClient->ip, newClient->port);

    // 끝났습니다. 클라이언트에게 정상적으로 접속했다고 알립니다.
    readMsg(newClient->socket, head, value);
    writeMsg(newClient->socket, ACCEPT, "server_ok");

    return newClient;
}
Ejemplo n.º 9
0
 Shape *MakeEmulated(BlockSet &Blocks, Block *Entry, BlockSet &NextEntries) {
   PrintDebug("creating emulated block with entry #%d and everything it can reach, %d blocks\n", Entry->Id, Blocks.size());
   EmulatedShape *Emulated = new EmulatedShape;
   Notice(Emulated);
   Emulated->Entry = Entry;
   for (BlockSet::iterator iter = Blocks.begin(); iter != Blocks.end(); iter++) {
     Block *Curr = *iter;
     Emulated->Blocks.insert(Curr);
     Curr->Parent = Emulated;
     Solipsize(Curr, Branch::Continue, Emulated, Blocks);
   }
   Blocks.clear();
   return Emulated;
 }
Ejemplo n.º 10
0
 Shape *MakeSimple(BlockSet &Blocks, Block *Inner, BlockSet &NextEntries) {
   PrintDebug("creating simple block with block #%d\n", Inner->Id);
   SimpleShape *Simple = new SimpleShape;
   Notice(Simple);
   Simple->Inner = Inner;
   Inner->Parent = Simple;
   if (Blocks.size() > 1) {
     Blocks.erase(Inner);
     GetBlocksOut(Inner, NextEntries, &Blocks);
     BlockSet JustInner;
     JustInner.insert(Inner);
     for (BlockSet::iterator iter = NextEntries.begin(); iter != NextEntries.end(); iter++) {
       Solipsize(*iter, Branch::Direct, Simple, JustInner);
     }
   }
   return Simple;
 }
Ejemplo n.º 11
0
 Shape *MakeMultiple(BlockSet &Blocks, BlockSet& Entries, BlockBlockSetMap& IndependentGroups, Shape *Prev, BlockSet &NextEntries) {
   PrintDebug("creating multiple block with %d inner groups\n", IndependentGroups.size());
   bool Fused = !!(Shape::IsSimple(Prev));
   MultipleShape *Multiple = new MultipleShape();
   Notice(Multiple);
   BlockSet CurrEntries;
   for (BlockBlockSetMap::iterator iter = IndependentGroups.begin(); iter != IndependentGroups.end(); iter++) {
     Block *CurrEntry = iter->first;
     BlockSet &CurrBlocks = iter->second;
     PrintDebug("  multiple group with entry %d:\n", CurrEntry->Id);
     DebugDump(CurrBlocks, "    ");
     // Create inner block
     CurrEntries.clear();
     CurrEntries.insert(CurrEntry);
     for (BlockSet::iterator iter = CurrBlocks.begin(); iter != CurrBlocks.end(); iter++) {
       Block *CurrInner = *iter;
       // Remove the block from the remaining blocks
       Blocks.erase(CurrInner);
       // Find new next entries and fix branches to them
       for (BlockBranchMap::iterator iter = CurrInner->BranchesOut.begin(); iter != CurrInner->BranchesOut.end();) {
         Block *CurrTarget = iter->first;
         BlockBranchMap::iterator Next = iter;
         Next++;
         if (CurrBlocks.find(CurrTarget) == CurrBlocks.end()) {
           NextEntries.insert(CurrTarget);
           Solipsize(CurrTarget, Branch::Break, Multiple, CurrBlocks); 
         }
         iter = Next; // increment carefully because Solipsize can remove us
       }
     }
     Multiple->InnerMap[CurrEntry] = Process(CurrBlocks, CurrEntries, NULL);
     // If we are not fused, then our entries will actually be checked
     if (!Fused) {
       CurrEntry->IsCheckedMultipleEntry = true;
     }
   }
   DebugDump(Blocks, "  remaining blocks after multiple:");
   // Add entries not handled as next entries, they are deferred
   for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
     Block *Entry = *iter;
     if (IndependentGroups.find(Entry) == IndependentGroups.end()) {
       NextEntries.insert(Entry);
     }
   }
   return Multiple;
 }
Ejemplo n.º 12
0
bool JobManager::processJobs()
{
    m_jobCount = 0;
    m_jobsNotIdle = 0;
    std::list<JobQueue*>::const_iterator it = m_queues.begin();
    for (; it != m_queues.end(); ++it)
        m_jobCount += (*it)->jobCount();

    m_jobsProcessed = 0;
    while (!m_errorOccured && m_jobsProcessed < m_jobCount) {
        // Select a valid queue
        std::list<JobQueue*>::iterator queueIt = m_queues.begin();
        JobQueue* queue = *queueIt;
        while (queue->hasShowStoppers() || queue->isEmpty()) {
            queue = *(++queueIt);
            if (queueIt == m_queues.end())
                goto finish;
        }

        MutexLocker locker(&m_jobsRunningMutex);
        if (m_jobsRunning >= m_maxJobsRunning)
            pthread_cond_wait(&m_needJobsCond, &m_jobsRunningMutex);

        if (m_errorOccured)
            break;

        // Now select a valid job
        if (Job* job = queue->getNextJob()) {
            job->addJobListenner(this);
            job->run();
            m_jobsRunning++;
            m_jobsNotIdle++;
            printReportLine(job);
        }
    }

    finish:

    MutexLocker locker(&m_jobsRunningMutex);
    if (m_jobsRunning) {
        Notice() << "Waiting for unfinished jobs...";
        pthread_cond_wait(&m_allDoneCond, &m_jobsRunningMutex);
    }

    return !m_errorOccured;
}
Ejemplo n.º 13
0
static int open_unix_socket () {
	int oldUmask;
	int request;

	unsock.sun_family = AF_UNIX;
	oldUmask = umask (0);
#ifdef X_UNIX_DIR
	mkdir (X_UNIX_DIR, 0777);
#endif
	strcpy (unsock.sun_path, X_UNIX_PATH);
	strcat (unsock.sun_path, display);
	unlink (unsock.sun_path);
	if ((request = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
		Notice ("Creating Unix socket");
	} else {
		if(bind(request,(struct sockaddr *)&unsock, strlen(unsock.sun_path)+2))
			Error ("Binding Unix socket");
		if (listen (request, 5)) Error ("Unix Listening");
	}
	(void)umask(oldUmask);
	return request;
}
Ejemplo n.º 14
0
void JobManager::printReportLine(const Job* job) const
{
    int perc = int((100 * m_jobsNotIdle) / m_jobCount);
    Manipulators color = NoColor;
    const char* text = "";

    switch (job->type()) {
    case Job::Compilation:
        color = Green;
        text = "Compiling ";
        break;
    case Job::Linking:
        color = Red;
        text = "Linking ";
        break;
    case Job::CustomTarget:
        color = Blue;
        text = "Running custom target function for ";
        break;
    }

    Notice() << '[' << perc << "%] " << color << text << job->name();
}
Ejemplo n.º 15
0
int main(int argc, char* argv[]) {
    int serverSocket;

    // 초기화
    front = 0;
    clientCount = 0;
    shellClient = 0;
    currentClient = 0;
    elapseTime = 0;

    Notice("Server process mode ON\n");

    if ( -1 == pipe(serverPipe) ) {
        perror("ERROR open pipe");
        exit(1);
    }
    Notice("Server pipe created\n");

    Notice("Trying to open socket...");

    // 들어오는 소켓 설정
    serverSocket = setSocket(INPORT);

    if (serverSocket < 0) {
        Notice("Error opening socket\n");
        exit(1);
    }
    printf("done.\n");

    Notice("Now waiting clients...\n");
    while (1) {
        // 소켓으로부터 클라이언트를 받아, 클라이언트 관리 리스트에 추가하고, 새 프로세스를 만듭니다.
        split( addClient( getClient(serverSocket) ) );

        // 클라이언트 개수가 MAX_CLIENT(=100)개라면 걸린 시간을 출력합니다.
        if (clientCount == MAX_CLIENT) {
            Notice("Process creation time");
            printf("(%d) : %lldns\n", clientCount, elapseTime);
        }

    }
}
Ejemplo n.º 16
0
void doShellMode(int socket) {
    char head[HEAD_SIZE], value[VALUE_SIZE];
    char buffer[VALUE_SIZE];
    char fileBuffer[FILE_BUFFER_SIZE + 1];

    int fd;

    // shell 모드로 작동합니다.
    while (true) {
        printf("SHELL #> ");
        fgets(buffer, VALUE_SIZE, stdin);

        // 기본 인터페이스
        if ( !strcmp(buffer, "usage") || !strcmp(buffer, "help") ) {
            printf("usage: (add|delete) filename\n");
            continue;
        } else
        if ( buffer[0] == '\n' ) {
            continue;
        }

        // 버퍼로부터 메시지를 분리해냅니다.
        sscanf(buffer, "%s %s", head, value);

        // 파일 추가
        if ( !strcmp(head, "add") ) {
            fd = open(value, O_RDONLY);
            // 없는 파일일 경우의 예외 처리
            if (fd == -1) {
                Notice("Cannot find ");
                printf("%s\n", value);
                continue;
            }

            // 서버에 파일을 전송할 것임을 알립니다.
            writeMsg(socket, ADD, value);
            readMsg(socket, head, value);

            // 서버에서 거부하는 경우 전송을 취소합니다.
            if ( strcmp(head, ACCEPT) != 0 ) {
                Notice("Denied by server.\n");
                continue;
            }

            // 서버에 파일 구분자를 보냅니다.
            writeMsg(socket, CHUNK, CHUNK_MSG);
            readMsg(socket, head, value);

            // 파일을 읽어서 그대로 전송합니다. 파일에서 읽을 때는 readData를 쓰지 않습니다.
            memset(fileBuffer, 0, sizeof(fileBuffer));
            while ( 0 < read(fd, fileBuffer, FILE_BUFFER_SIZE - 1) ) {
                writeData(socket, fileBuffer);
                readMsg(socket, head, value);
                memset(fileBuffer, 0, sizeof(fileBuffer));
            }

            // 전송이 완료되었으므로, 파일 구분자를 보냅니다.
            writeData(socket, CHUNK_MSG);
            close(fd);
            // eof 메시지를 확인합니다.
            readMsg(socket, head, value);

        } else
        // 파일을 삭제하는 경우
        if ( !strcmp(head, "delete") ) {
            // 서버에 파일을 삭제할 것을 요청하고, 로컬에서도 파일을 지웁니다.
            writeMsg(socket, DEL, value);
            remove (value);
        }
        else {
            printf("Unknown command\n");
            printf("usage: (add|delete) filename\n");
            continue;
        }
    }
}
Ejemplo n.º 17
0
void doShell(Client* shellClient) {
    Client* p;
    char head[HEAD_SIZE], value[VALUE_SIZE];

    char fileBuffer[FILE_BUFFER_SIZE + 1];
    char fileChunk[FILE_CHUNK_SIZE];
    char filename[256];
    unsigned long fileSize;
    int fd;
    FILE* fp;

    FDEBUG(("shell start\n"));
    while (1) {
        // shell 담당 서버는 shell 클라이언트로부터 신호를 받아야만 일합니다.
        readMsg(shellClient->socket, head, value);

        if ( !strcmp(head, ADD) ) {
            // 파일 추가
            FDEBUG(("get ADD message\n"));
            fileSize = 0;

            // 우선 해당 이름으로 파일을 엽니다.
            strcpy(filename, value);
            fd = open(filename, O_WRONLY | O_CREAT, 0644);
            if (fd == -1) {
                writeMsg(shellClient->socket, ERR, "fileopen_err");
                continue;
            }

            // 다른 일반 클라이언트들에게도 이 사실을 알립니다.
            writeMsg(shellClient->socket, ACCEPT, "fileadd");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ADD, filename);
                p = p->nextClient;
            }

            // 파일 구분자를 입력받습니다.
            readMsg(shellClient->socket, head, fileChunk);
            writeMsg(shellClient->socket, ACCEPT, "filechunk");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], CHUNK, fileChunk);
                p = p->nextClient;
            }

            // 파일을 읽어서 클라이언트에게 전달합니다. 서버에도 한 부 저장합니다.
            FDEBUG(("start reading file\n"));
            while (true) {
                memset(fileBuffer, 0, sizeof(fileBuffer));
                readData(shellClient->socket, fileBuffer);

                p = front;
                while (p) {
                    writeData(p->pipe[1], fileBuffer);
                    p = p->nextClient;
                }

                // 파일 전송이 끝나면 끝냅니다.
                if ( !strcmp(fileBuffer, fileChunk) ) break;
                // 아니라면 서버에 저장하고 다음 부분을 보내달라고 요청합니다.
                else writeData(fd, fileBuffer);
                writeMsg(shellClient->socket, CHUNK, fileChunk);
                fileSize += strlen(fileBuffer);
            }
            // 파일을 전부 기록했습니다. 닫고 EOF 메시지를 전달합니다.
            close(fd);
            writeMsg(shellClient->socket, ACCEPT, "eof");
            p = front;
            while (p) {
                writeMsg(p->pipe[1], ACCEPT, "eof");
                p = p->nextClient;
            }

            // 결과를 출력합니다.
            Notice("ADD ");
            printf("[%s][%ldbyte] from Client(%d)\n", filename, fileSize, shellClient->clientNo);

        } else
        if ( !strcmp(head, DEL) ) {
            // 삭제할 파일의 크기를 구합니다.
            fp = fopen(value, "r");
            fseek(fp, 0L, SEEK_END);
            fileSize = ftell(fp);
            fclose(fp);

            // 결과를 출력합니다.
            Notice ("DELETE ");
            printf("[%s][%ldbyte] from Client(%d)\n", value, fileSize, shellClient->clientNo);

            // 파일을 삭제하고 다른 클라이언트에게 알립니다.
            remove( value );

            p = front;
            while (p) {
                writeMsg(p->pipe[1], head, value);
                p = p->nextClient;
            }

        }
    }
}
Ejemplo n.º 18
0
int init(int portno, char* hostname, bool isShell) {
    int sock_cli, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char head[HEAD_SIZE], value[VALUE_SIZE];

    Notice("Trying to make socket\n");

    // 소켓 통신을 위한 설정을 진행합니다.
    sock_cli = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_cli < 0) {
        perror("ERROR opening socket");
    }

    server = gethostbyname(hostname);
    if (server == NULL) {
        perror("ERROR: no such host");
        exit(0);
    }

    memset( (char*) &serv_addr, 0, sizeof(serv_addr) );
    serv_addr.sin_family = AF_INET;
    bcopy( (char*) server->h_addr, (char*) &serv_addr.sin_addr.s_addr, server->h_length );
    serv_addr.sin_port = htons(portno);

    Notice("Trying to connect server");
    printf(" %s...", hostname);
    fflush(stdout);
    if ( connect(sock_cli, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0 ) {
        perror("ERROR connecting");
        exit(1);
    }

    // 서버 접속 완료
    printf("Connected. Initiating...");

    // shell 모드인지 아닌지를 서버에 알립니다.
    if (isShell) writeMsg(sock_cli, MODE, MODE_SHELL);
    else writeMsg(sock_cli, MODE, MODE_CLIENT);

    // 서버에서의 내 이름을 받아옵니다.
    readMsg(sock_cli, head, value);
    if ( !strcmp(head, SET_NAME) ) {
        strcpy(clientName, value);
        writeMsg(sock_cli, SET_NAME, "ok");
    } else {
        printf("Error during initiation\n");
        exit(1);
    }

    // 처리가 완료되었는지를 다시 한 번 확인합니다.
    readMsg(sock_cli, head, value);
    if ( !strcmp(head, ACCEPT) ) {
        printf("done.\n");
    } else {
        printf("Error during initiation\n");
        exit(1);
    }

    return sock_cli;
}
Ejemplo n.º 19
0
void
CreateWellKnownSockets() {
	int		request, i;
	int		whichbyte;	    /* used to figure out whether this is
   					 LSB or MSB */
#ifdef TCPCONN
	struct sockaddr_in insock;
	int		tcpportReg;	    /* port with same byte order as server */

#ifdef SO_LINGER
	static int linger[2] = { 0, 0 };
#endif /* SO_LINGER */

#endif /* TCPCONN */

#ifdef DNETCONN
	struct sockaddr_dn dnsock;
#endif /* DNETCONN */

#ifdef ISOCONN
	struct TSAPdisconnect tds;
	struct TSAPdisconnect *td = &tds;
	struct TSAPaddr tas;
	struct TSAPaddr *ta = &tas;
	struct PSAPaddr *pa;
	AEI   aei;
#endif /* ISOCONN */
	int retry;

#ifdef ISOCONN
#ifdef ISODEBUG
	isodetcpath = ISODEPATH;
#endif
#endif /* ISOCONN */

	CLEARBITS(AllSockets);
	CLEARBITS(AllClients);
	CLEARBITS(LastSelectMask);
	CLEARBITS(ClientsWithInput);

	for (i=0; i<MAXSOCKS; i++) ConnectionTranslation[i] = (ClientPtr)NULL;

#ifdef	hpux
	lastfdesc = _NFILE - 1;
#else
	lastfdesc = getdtablesize() - 1;
#endif	/* hpux */

	if (lastfdesc > MAXSOCKS) {
		lastfdesc = MAXSOCKS;
		if (debug_conns)
			ErrorF( "GOT TO END OF SOCKETS %d\n", MAXSOCKS);
	}

	WellKnownConnections = 0;
	whichbyte = 1;

	if (*(char *) &whichbyte)
		whichByteIsFirst = 'l';
	else
		whichByteIsFirst = 'B';


#ifdef TCPCONN

	tcpportReg = atoi (display);
	tcpportReg += X_TCP_PORT;

	if ((request = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
		Notice ("Creating TCP socket");
	} else {
		bzero ((char *)&insock, sizeof (insock));
		insock.sin_family = AF_INET;
		insock.sin_port = htons (tcpportReg);
		insock.sin_addr.s_addr = htonl(INADDR_ANY);
		retry = 20;
		while (i = bind(request, (struct sockaddr *) &insock, sizeof (insock))) {
#ifdef hpux
			/* Necesary to restart the server without a reboot */
			if (errno == EADDRINUSE)
				set_socket_option (request, SO_REUSEADDR);
			if (--retry == 0)
				Error ("Binding TCP socket");
			sleep (1);
#else
			if (--retry == 0)
				Error ("Binding MSB TCP socket");
			sleep (10);
#endif /* hpux */
		}
#ifdef hpux
		/* return the socket option to the original */
		if (errno)
			unset_socket_option (request, SO_REUSEADDR);
#endif /* hpux */
#ifdef SO_LINGER
		if(setsockopt (request, SOL_SOCKET, SO_LINGER,
					   (char *)linger, sizeof(linger)))
			Notice ("Setting TCP SO_LINGER\n");
#endif /* SO_LINGER */
		if (listen (request, 5))
			Error ("Reg TCP Listening");
		WellKnownConnections |= (1 << request);
		DefineSelf (request);
#ifdef ISOCONN
		fd2family[request] = UNIX_IO;
#endif /* ISOCONN */
	}

#endif /* TCPCONN */

#ifdef UNIXCONN
	if ((request = open_unix_socket ()) != -1) {
		WellKnownConnections |= (1L << request);
		unixDomainConnection = request;
#ifdef ISOCONN
		fd2family[request] = UNIX_IO;
#endif /* ISOCONN */
	}
#endif /*UNIXCONN */

#ifdef DNETCONN
	if ((request = socket (AF_DECnet, SOCK_STREAM, 0)) < 0) {
		Notice ("Creating DECnet socket");
	} else {
		bzero ((char *)&dnsock, sizeof (dnsock));
		dnsock.sdn_family = AF_DECnet;
		sprintf(dnsock.sdn_objname, "X$X%d", atoi (display));
		dnsock.sdn_objnamel = strlen(dnsock.sdn_objname);
		if (bind (request, (struct sockaddr *) &dnsock, sizeof (dnsock)))
			Error ("Binding DECnet socket");
		if (listen (request, 5)) Error ("DECnet Listening");
		WellKnownConnections |= (1 << request);
		DefineSelf (request);
#ifdef ISOCONN
		fd2family[request] = UNIX_IO;
#endif /* ISOCONN */
	}
#endif /* DNETCONN */
#ifdef ISOCONN
	/*
	 * If display is set, its the string after the Colon:
	 * i.e. X0 or X1 or T0 or T1...
	 */
	if ((display == NULLCP) || (atoi(display) == 0))
		aei = str2aei(TLocalHostName(), DEFAULTTSERVICE);
	else
		aei = str2aei(TLocalHostName(), display);

	if (aei == NULLAEI) {
		ErrorF("No AEI for me:");
		FatalError(TLocalHostName());
	}

	/*
	 * This hack only works if the PSAPaddr and SSAP addrsd are null!!
	 */
	if ((pa = aei2addr (aei)) == NULLPA)
		FatalError("address translation failed");

	ta = (struct TSAPaddr *)&(pa->pa_addr.sa_addr);

	/*
	 * Just put out a listen for now
	 */
	if ((request = TNetListen(ta, td)) != OK) {
		Error(TErrString(td->td_reason));
		FatalError("TNetListen");
	}

	WellKnownConnections |= (1 << request);
	DefineSelf (request);
	fd2family[request] = ISODE_IO;
#endif /*  ISOCONN */
	if (WellKnownConnections == 0)
		Error ("No Listeners, nothing to do");
	signal (SIGPIPE, SIG_IGN);
	signal (SIGHUP, AutoResetServer);
	signal (SIGINT, GiveUp);
	signal (SIGTERM, GiveUp);
	FirstClient = request + 1;
	AllSockets[0] = WellKnownConnections;
	ResetHosts(display);

	for (i=0; i<MaxClients; i++) {
		inputBuffers[i].buffer = (char *) NULL;
		inputBuffers[i].bufptr = (char *) NULL;
		inputBuffers[i].bufcnt = 0;
		inputBuffers[i].lenLastReq = 0;
		inputBuffers[i].size = 0;
	}
}
Ejemplo n.º 20
0
/*********************************************************************************

	bool CVotePageBuilder::GetCommonInfo(bool bGetVoteInfo)

		Author:		Mark Howitt
        Created:	21/05/2004
        Inputs:		bGetVoteInfo - A flag that when true includes the info 
					on the current vote id
					bNeedResponseInfo - true to include <RESPONSE> element.
						response cgi parameter must be set
        Outputs:	-
        Returns:	-
        Purpose:	Gets all the common information on the current vote.

*********************************************************************************/
bool CVotePageBuilder::GetCommonInfo(bool bGetVoteInfo, bool bNeedResponseInfo)
{
	// Get the current user
	CUser* pViewingUser = m_InputContext.GetCurrentUser();
	m_iUserID = 0;
	if (pViewingUser)
	{
		// Get the id of the current viewing user
		m_iUserID = pViewingUser->GetUserID();
	}

	// Get the UID For the current user.
	m_InputContext.GetBBCUIDFromCookie(m_sBBCUID);
	
	// Initialise the XML Builder ready to create the XML
	CStoredProcedure SP;
	CTDVString sXML;
	CDBXMLBuilder XML;
	XML.Initialise(&sXML,&SP);

	// Start with the USER info
	bool bOk = XML.OpenTag("USER");
	bOk = bOk && XML.AddIntTag("USERID",m_iUserID);

	// Get the user name if we have a valid UserID
	if (m_iUserID > 0)
	{
		m_InputContext.InitialiseStoredProcedureObject(&SP);
		if (!SP.GetUserDetailsFromID(m_iUserID,m_InputContext.GetSiteID()))
		{
			TDVASSERT(false, "Failed to find user name from id");
		}
		else
		{
			bOk = bOk && XML.DBAddTag("USERNAME",NULL,true,true,&m_sUserName);
			bOk = bOk && XML.DBAddTag("FIRSTNAMES",NULL,false);
			bOk = bOk && XML.DBAddTag("LASTNAME",NULL,false);
			bOk = bOk && XML.DBAddTag("AREA",NULL,false);
			bOk = bOk && XML.DBAddTag("TITLE",NULL,false);			
			bOk = bOk && XML.DBAddTag("SITESUFFIX",NULL,false);			
			bOk = bOk && XML.DBAddIntTag("JOURNAL", NULL, false);				
			bOk = bOk && XML.DBAddIntTag("STATUS", NULL, false);
			bOk = bOk && XML.DBAddIntTag("TAXONOMYNODE", NULL, false);
			bOk = bOk && XML.DBAddIntTag("ACTIVE");		

			//get the groups to which this user belongs to 		
			CTDVString sGroupXML;		
			bOk = bOk && m_InputContext.GetUserGroups(sGroupXML, m_iUserID);
			sXML = sXML + sGroupXML;
		}
	}

	// Close and add to the page
	bOk = bOk && XML.CloseTag("USER");
	bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

	// Check to if we require vote info
	if (bOk && bGetVoteInfo)
	{
		// First get the vote ID
		m_iVoteID = m_InputContext.GetParamInt("voteid");

		// Now setup the Vote Object
		if (!m_CurrentVote.GetVote(m_iVoteID))
		{
			m_pPage->SetError("InvalidVoteID"); 
			return false;
		}

		// Get the type from the url
		m_iType = m_InputContext.GetParamInt("type");
		sXML.Empty();
		sXML << "<VOTETYPE>" << m_iType << "</VOTETYPE>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		// First check to see if the user has already voted!
		// If the user id is 0 then we need to do a cookie check!
		bool bAlreadyVoted = false;
		if (!m_CurrentVote.HasUserAlreadyVoted(m_iVoteID,m_iUserID,m_sBBCUID,bAlreadyVoted))
		{
			m_pPage->SetError("FailedCheckingAlreadyVoted"); 
			return false;
		}

		sXML.Empty();
		sXML << "<ALREADYVOTED>" << bAlreadyVoted << "</ALREADYVOTED>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		// Check to see if the current vote is closed?
		m_bVoteClosed = false;
		if (!m_CurrentVote.IsVoteClosed(m_bVoteClosed))
		{
			m_pPage->SetError("DontKnowIfVoteClosed"); 
			return false;
		}

		sXML.Empty();
		sXML << "<VOTECLOSED>" << m_bVoteClosed << "</VOTECLOSED>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		// Get the details from the vote
		m_CurrentVote.GetVoteName(m_sVoteName);
		sXML.Empty();
		sXML << "<VOTEID>" << m_iVoteID << "</VOTEID>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		sXML.Empty();
		sXML << "<VOTENAME>" << m_sVoteName << "</VOTENAME>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		// Get the club id for the vote
		m_iObjectID = 0;
		if (!m_CurrentVote.GetObjectIDFromVoteID(m_iVoteID,m_iType,m_iObjectID))
		{
			m_pPage->SetError("InvalidObjectID");
			return false;
		}

		// Output the correct type of XML
		if (m_iType == VOTETYPE_CLUB)
		{
			sXML.Empty();
			sXML << "<OBJECT TYPE='CLUB' ID='" << m_iObjectID << "'/>";
			bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

			// Get the Club OwnerID
			CClub Club(m_InputContext);
			Club.InitialiseViaClubID(m_iObjectID);
			m_iOwnerID = Club.GetOwnerTeamID();
		}
		else if (m_iType == VOTETYPE_NOTICE)
		{
			// Get the NodeID from the ThreadID
			// Copy the Object id passed in through th eurl into the threadid varaible as the objectid
			// is actually the threadid for the notice being voted on.
			m_iThreadID = m_iObjectID;
			CNotice Notice(m_InputContext);
			Notice.GetNodeIDFromThreadID(m_iThreadID,m_InputContext.GetSiteID(),m_iObjectID);
			CTDVString sPostCode;
			m_InputContext.GetParamString("postcode",sPostCode);
			sXML.Empty();
			sXML << "<OBJECT TYPE='NOTICE' ID='" << m_iObjectID << "' POSTCODE='" << sPostCode << "'/>";
			bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);
		}
		else
		{
			m_pPage->SetError("InvalidObjectID");
			return false;
		}

		if (bNeedResponseInfo)
		{
			// Get the users response
			if (!m_InputContext.ParamExists("response"))
			{
				m_pPage->SetError("NoResponse");
				return false;
			}
			m_iResponse = m_InputContext.GetParamInt("response");
			sXML.Empty();
			sXML << "<RESPONSE>" << m_iResponse << "</RESPONSE>";
			bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);
		}

		// Now get the date the vote was created
		CTDVString sDate;
		m_CurrentVote.GetCreatedDate(m_tDateCreated);
		m_tDateCreated.GetRelativeDate(sDate);
		sXML.Empty();
		sXML << "<DATECREATED>" << sDate << "</DATECREATED>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);

		// Now get the closing date for the vote
		sDate.Empty();
		m_CurrentVote.GetClosingDate(m_tClosingDate);
		if (m_tClosingDate != NULL)
		{
			sDate << (-m_tClosingDate.DaysElapsed());
		}
		sXML.Empty();
		sXML << "<CLOSINGDATE>" << sDate << "</CLOSINGDATE>";
		bOk = bOk && m_pPage->AddInside("VOTING-PAGE",sXML);
	}

	// Set the error message if something went wrong.
	if (!bOk)
	{
		m_pPage->SetError("FailedAddingXMLToPage");
	}

	// Return Ok
	return bOk;
}
Ejemplo n.º 21
0
/* creates the listening socket, bind, applies options; waits for incoming
   connection, checks its source address and port. Depending on fork option, it
   may fork a subprocess.
   pf specifies the syntax expected for range option. In the case of generic
   socket it is 0 (expecting raw binary data), and the real pf can be obtained
   from us->af_family; for other socket types pf == us->af_family
   Returns 0 if a connection was accepted; with fork option, this is always in
   a subprocess!
   Other return values indicate a problem; this can happen in the master
   process or in a subprocess.
   This function does not retry. If you need retries, handle this in a
   loop in the calling function (and always provide the options...)
   After fork, we set the forever/retry of the child process to 0
   applies and consumes the following option:
   PH_INIT, PH_PASTSOCKET, PH_PREBIND, PH_BIND, PH_PASTBIND, PH_EARLY,
   PH_PREOPEN, PH_FD, PH_CONNECTED, PH_LATE, PH_LATE2
   OPT_FORK, OPT_SO_TYPE, OPT_SO_PROTOTYPE, OPT_BACKLOG, OPT_RANGE, tcpwrap,
   OPT_SOURCEPORT, OPT_LOWPORT, cloexec
 */
int _xioopen_listen(struct single *xfd, int xioflags, struct sockaddr *us, socklen_t uslen,
		 struct opt *opts, int pf, int socktype, int proto, int level) {
   struct sockaddr sa;
   socklen_t salen;
   int backlog = 5;	/* why? 1 seems to cause problems under some load */
   char *rangename;
   bool dofork = false;
   int maxchildren = 0;
   char infobuff[256];
   char lisname[256];
   union sockaddr_union _peername;
   union sockaddr_union _sockname;
   union sockaddr_union *pa = &_peername;	/* peer address */
   union sockaddr_union *la = &_sockname;	/* local address */
   socklen_t pas = sizeof(_peername);	/* peer address size */
   socklen_t las = sizeof(_sockname);	/* local address size */
   int result;

   retropt_bool(opts, OPT_FORK, &dofork);

   if (dofork) {
      if (!(xioflags & XIO_MAYFORK)) {
	 Error("option fork not allowed here");
	 return STAT_NORETRY;
      }
      xfd->flags |= XIO_DOESFORK;
   }

   retropt_int(opts, OPT_MAX_CHILDREN, &maxchildren);

   if (! dofork && maxchildren) {
       Error("option max-children not allowed without option fork");
       return STAT_NORETRY;
   }

   if (applyopts_single(xfd, opts, PH_INIT) < 0)  return -1;

   if (dofork) {
      xiosetchilddied();	/* set SIGCHLD handler */
   }

   if ((xfd->fd = xiosocket(opts, us->sa_family, socktype, proto, level)) < 0) {
      return STAT_RETRYLATER;
   }

   applyopts_cloexec(xfd->fd, opts);

   applyopts(xfd->fd, opts, PH_PREBIND);
   applyopts(xfd->fd, opts, PH_BIND);
   if (Bind(xfd->fd, (struct sockaddr *)us, uslen) < 0) {
      Msg4(level, "bind(%d, {%s}, "F_socklen"): %s", xfd->fd,
	   sockaddr_info(us, uslen, infobuff, sizeof(infobuff)), uslen,
	   strerror(errno));
      Close(xfd->fd);
      return STAT_RETRYLATER;
   }

#if WITH_UNIX
   if (us->sa_family == AF_UNIX) {
      applyopts_named(((struct sockaddr_un *)us)->sun_path, opts, PH_FD);
   }
#endif
   /* under some circumstances (e.g., TCP listen on port 0) bind() fills empty
      fields that we want to know. */
   salen = sizeof(sa);
   if (Getsockname(xfd->fd, us, &uslen) < 0) {
      Warn4("getsockname(%d, %p, {%d}): %s",
	    xfd->fd, &us, uslen, strerror(errno));
   }

   applyopts(xfd->fd, opts, PH_PASTBIND);
#if WITH_UNIX
   if (us->sa_family == AF_UNIX) {
      /*applyopts_early(((struct sockaddr_un *)us)->sun_path, opts);*/
      applyopts_named(((struct sockaddr_un *)us)->sun_path, opts, PH_EARLY);
      applyopts_named(((struct sockaddr_un *)us)->sun_path, opts, PH_PREOPEN);
   }
#endif /* WITH_UNIX */

#if WITH_IP4 /*|| WITH_IP6*/
   if (retropt_string(opts, OPT_RANGE, &rangename) >= 0) {
      if (xioparserange(rangename, pf, &xfd->para.socket.range)
	  < 0) {
	 free(rangename);
	 return STAT_NORETRY;
      }
      free(rangename);
      xfd->para.socket.dorange = true;
   }
#endif

#if (WITH_TCP || WITH_UDP) && WITH_LIBWRAP
   xio_retropt_tcpwrap(xfd, opts);
#endif /* && (WITH_TCP || WITH_UDP) && WITH_LIBWRAP */

#if WITH_TCP || WITH_UDP
   if (retropt_ushort(opts, OPT_SOURCEPORT, &xfd->para.socket.ip.sourceport) >= 0) {
      xfd->para.socket.ip.dosourceport = true;
   }
   retropt_bool(opts, OPT_LOWPORT, &xfd->para.socket.ip.lowport);
#endif /* WITH_TCP || WITH_UDP */

   applyopts(xfd->fd, opts, PH_PRELISTEN);
   retropt_int(opts, OPT_BACKLOG, &backlog);
   if (Listen(xfd->fd, backlog) < 0) {
      Error3("listen(%d, %d): %s", xfd->fd, backlog, strerror(errno));
      return STAT_RETRYLATER;
   }

   if (xioopts.logopt == 'm') {
      Info("starting accept loop, switching to syslog");
      diag_set('y', xioopts.syslogfac);  xioopts.logopt = 'y';
   } else {
      Info("starting accept loop");
   }
   while (true) {	/* but we only loop if fork option is set */
      char peername[256];
      char sockname[256];
      int ps;		/* peer socket */

      pa = &_peername;
      la = &_sockname;
      salen = sizeof(struct sockaddr);
      do {
	 /*? int level = E_ERROR;*/
	 Notice1("listening on %s", sockaddr_info(us, uslen, lisname, sizeof(lisname)));
	 ps = Accept(xfd->fd, (struct sockaddr *)&sa, &salen);
	 if (ps >= 0) {
	    /*0 Info4("accept(%d, %p, {"F_Zu"}) -> %d", xfd->fd, &sa, salen, ps);*/
	    break;	/* success, break out of loop */
	 }
	 if (errno == EINTR) {
	    continue;
	 }
	 if (errno == ECONNABORTED) {
	    Notice4("accept(%d, %p, {"F_socklen"}): %s",
		    xfd->fd, &sa, salen, strerror(errno));
	    continue;
	 }
	 Msg4(level, "accept(%d, %p, {"F_socklen"}): %s",
	      xfd->fd, &sa, salen, strerror(errno));
	 Close(xfd->fd);
	 return STAT_RETRYLATER;
      } while (true);
      applyopts_cloexec(ps, opts);
      if (Getpeername(ps, &pa->soa, &pas) < 0) {
	 Warn4("getpeername(%d, %p, {"F_socklen"}): %s",
	       ps, pa, pas, strerror(errno));
	 pa = NULL;
      }
      if (Getsockname(ps, &la->soa, &las) < 0) {
	 Warn4("getsockname(%d, %p, {"F_socklen"}): %s",
	       ps, la, las, strerror(errno));
	 la = NULL;
      }
      Notice2("accepting connection from %s on %s",
	      pa?
	      sockaddr_info(&pa->soa, pas, peername, sizeof(peername)):"NULL",
	      la?
	      sockaddr_info(&la->soa, las, sockname, sizeof(sockname)):"NULL");

      if (pa != NULL && la != NULL && xiocheckpeer(xfd, pa, la) < 0) {
	 if (Shutdown(ps, 2) < 0) {
	    Info2("shutdown(%d, 2): %s", ps, strerror(errno));
	 }
	 Close(ps);
	 continue;
      }

      if (pa != NULL)
	 Info1("permitting connection from %s",
	       sockaddr_info((struct sockaddr *)pa, pas,
			     infobuff, sizeof(infobuff)));

      if (dofork) {
	 pid_t pid;	/* mostly int; only used with fork */
         sigset_t mask_sigchld;

         /* we must prevent that the current packet triggers another fork;
            therefore we wait for a signal from the recent child: USR1
            indicates that is has consumed the last packet; CHLD means it has
            terminated */
         /* block SIGCHLD and SIGUSR1 until parent is ready to react */
         sigemptyset(&mask_sigchld);
         sigaddset(&mask_sigchld, SIGCHLD);
         Sigprocmask(SIG_BLOCK, &mask_sigchld, NULL);

	 if ((pid = xio_fork(false, level==E_ERROR?level:E_WARN)) < 0) {
	    Close(xfd->fd);
	    Sigprocmask(SIG_UNBLOCK, &mask_sigchld, NULL);
	    return STAT_RETRYLATER;
	 }
	 if (pid == 0) {	/* child */
	    pid_t cpid = Getpid();
	    Sigprocmask(SIG_UNBLOCK, &mask_sigchld, NULL);

	    Info1("just born: child process "F_pid, cpid);
	    xiosetenvulong("PID", cpid, 1);

	    if (Close(xfd->fd) < 0) {
	       Info2("close(%d): %s", xfd->fd, strerror(errno));
	    }
	    xfd->fd = ps;

#if WITH_RETRY
	    /* !? */
	    xfd->forever = false;  xfd->retry = 0;
	    level = E_ERROR;
#endif /* WITH_RETRY */

	    break;
	 }

	 /* server: continue loop with listen */
	 /* shutdown() closes the socket even for the child process, but
	    close() does what we want */
	 if (Close(ps) < 0) {
	    Info2("close(%d): %s", ps, strerror(errno));
	 }

         /* now we are ready to handle signals */
         Sigprocmask(SIG_UNBLOCK, &mask_sigchld, NULL);

	 while (maxchildren) {
	    if (num_child < maxchildren) break;
	    Notice("maxchildren are active, waiting");
	    /* UINT_MAX would even be nicer, but Openindiana works only
	       with 31 bits */
	    while (!Sleep(INT_MAX)) ;	/* any signal lets us continue */
	 }
	 Info("still listening");
      } else {
	 if (Close(xfd->fd) < 0) {
	    Info2("close(%d): %s", xfd->fd, strerror(errno));
	 }
	 xfd->fd = ps;
	break;
      }
   }

   applyopts(xfd->fd, opts, PH_FD);
   applyopts(xfd->fd, opts, PH_PASTSOCKET);
   applyopts(xfd->fd, opts, PH_CONNECTED);
   if ((result = _xio_openlate(xfd, opts)) < 0)
      return result;

   /* set the env vars describing the local and remote sockets */
   if (la != NULL)  xiosetsockaddrenv("SOCK", la, las, proto);
   if (pa != NULL)  xiosetsockaddrenv("PEER", pa, pas, proto);

   return 0;
}
Ejemplo n.º 22
0
/* process a bidirectional "stdio" or "-" argument with options. */
int xioopen_stdio_bi(xiofile_t *sock) {
   struct opt *opts1, *opts2, *optspr;
   unsigned int groups1 = xioaddr_stdio0.groups, groups2 = xioaddr_stdio0.groups;
   int result;

   sock->stream.rfd = 0 /*stdin*/;
   sock->stream.wfd = 1 /*stdout*/;

#if WITH_TERMIOS
   if (Isatty(sock->stream.rfd)) {
      if (Tcgetattr(sock->stream.rfd,
		    &sock->stream.savetty)
	  < 0) {
	 Warn2("cannot query current terminal settings on fd %d: %s",
	       sock->stream.rfd, strerror(errno));
      } else {
	 sock->stream.ttyvalid = true;
      }
   }
   if (Isatty(sock->stream.wfd) && (sock->stream.wfd != sock->stream.rfd)) {
      if (Tcgetattr(sock->stream.wfd,
		    &sock->stream.savetty)
	  < 0) {
	 Warn2("cannot query current terminal settings on fd %d: %s",
	       sock->stream.wfd, strerror(errno));
      } else {
	 sock->stream.ttyvalid = true;
      }
   }
#endif /* WITH_TERMIOS */
   if (applyopts_single(&sock->stream, sock->stream.opts, PH_INIT) < 0)
      return -1;
   applyopts(-1, sock->stream.opts, PH_INIT);
   if (sock->stream.howtoshut == XIOSHUT_UNSPEC)
      sock->stream.howtoshut = XIOSHUT_NONE;

   /* options here are one-time and one-direction, no second use */
   retropt_bool(sock->stream.opts, OPT_IGNOREEOF, &sock->stream.ignoreeof);

   /* extract opts that should be applied only once */
   if ((optspr = copyopts(sock->stream.opts, GROUP_PROCESS)) == NULL) {
      return -1;
   }
   if ((result = applyopts(-1, optspr, PH_EARLY)) < 0)
      return result;
   if ((result = applyopts(-1, optspr, PH_PREOPEN)) < 0)
      return result;

   /* here we copy opts, because most have to be applied twice! */
   if ((opts1 = copyopts(sock->stream.opts, GROUP_FD|GROUP_APPL|(groups1&~GROUP_PROCESS))) == NULL) {
      return -1;
   }

   /* apply options to first FD */
   if ((result = applyopts(sock->stream.rfd, opts1, PH_ALL)) < 0) {
      return result;
   }
   if ((result = _xio_openlate(&sock->stream, opts1)) < 0) {
      return result;
   }

   if ((opts2 = copyopts(sock->stream.opts, GROUP_FD|GROUP_APPL|(groups2&~GROUP_PROCESS))) == NULL) {
      return -1;
   }
   /* apply options to second FD */
   if ((result = applyopts(sock->stream.wfd, opts2, PH_ALL)) < 0) {
      return result;
   }
   if ((result = _xio_openlate(&sock->stream, opts2)) < 0) {
      return result;
   }

   if ((result = _xio_openlate(&sock->stream, optspr)) < 0) {
      return result;
   }

   Notice("reading from and writing to stdio");
   return 0;
}
Ejemplo n.º 23
0
void CWarMap::Timeout()
{
	SetTimeoutEvent(NULL);

	if (m_bTimeout)
		return;

	if (m_bEnded)
		return;

	DWORD dwWinner = 0;
	DWORD dwLoser = 0;
	int iRewardGold = 0;

	if (get_dword_time() - m_dwStartTime < 60000 * 5)
	{
		Notice(LC_TEXT("길드전이 일찍 종료되어 무승부로 판정 되었습니다. (5분이 지나지 않음)"));
		dwWinner = 0;
		dwLoser = 0;
	}
	else
	{
		int iWinnerIdx = -1;

		if (m_TeamData[0].iMemberCount == 0)
			iWinnerIdx = 1;
		else if (m_TeamData[1].iMemberCount == 0)
			iWinnerIdx = 0;

		if (iWinnerIdx == -1)
		{
			dwWinner = GetWinnerGuild();

			if (dwWinner == m_TeamData[0].dwID)
			{
				iRewardGold = GetRewardGold(0);
				dwLoser = m_TeamData[1].dwID;
			}
			else if (dwWinner == m_TeamData[1].dwID)
			{
				iRewardGold = GetRewardGold(1);
				dwLoser = m_TeamData[0].dwID;
			}

			sys_err("WarMap: member count is not zero, guild1 %u %d guild2 %u %d, winner %u",
					m_TeamData[0].dwID, m_TeamData[0].iMemberCount,
					m_TeamData[1].dwID, m_TeamData[1].iMemberCount,
					dwWinner);
		}
		else
		{
			dwWinner = m_TeamData[iWinnerIdx].dwID;
			dwLoser = m_TeamData[iWinnerIdx == 0 ? 1 : 0].dwID;

			iRewardGold = GetRewardGold(iWinnerIdx);
		}
	}

	sys_log(0, "WarMap: Timeout %u %u winner %u loser %u reward %d map %d",
			m_TeamData[0].dwID, m_TeamData[1].dwID, dwWinner, dwLoser, iRewardGold, m_kMapInfo.lMapIndex);

	if (dwWinner)
		CGuildManager::instance().RequestWarOver(dwWinner, dwLoser, dwWinner, iRewardGold);
	else
		CGuildManager::instance().RequestWarOver(m_TeamData[0].dwID, m_TeamData[1].dwID, dwWinner, iRewardGold);

	m_bTimeout = true;
}
Ejemplo n.º 24
0
bool CNoticeBoardList::GetNoticeBoardsForNodeID(const int iNodeID, const int iSiteID, int iSkip, int iShow)
{
    // First check to make sure we've been given correct params
    if (iNodeID <= 0 || iSiteID <= 0)
    {
        return SetDNALastError("CNoticeBoardList","InvalidCallParams","Invalid node or site id given!");
    }

    // Now try to create the object so we can add the noticeboard to it
    if (!CreateFromCacheText("<NOTICEBOARDLIST></NOTICEBOARDLIST>"))
    {
        return SetDNALastError("CNoticeBoardList","FailedToCreateTree","Failed to create the tree object");
    }

    // Now get the tree level for the given node
    CStoredProcedure SP;
    m_InputContext.InitialiseStoredProcedureObject(&SP);
    if (!SP.GetTreeLevelForNodeID(iNodeID,iSiteID))
    {
        return SetDNALastError("CNoticeBoardList","FailedToGetTreeLevel","Failed to get the tree level for the given node! Invalid nodeid?");
    }

    // Now get the value and move the results position
    int iTreeLevel = SP.GetIntField("TreeLevel");
    if (iTreeLevel < 3)
    {
        // We don't want to show noticeboard lists for anything above level 4!
        return true;
    }

    // We're higher, so get all the noticeboards from the child areas
    // Get all the local authority nodes under this node!
    if (!SP.GetAllLocalAuthorityNodes(iSiteID,iNodeID,5))
    {
        return SetDNALastError("CNoticeBoardList","FailedToGetNodes","Failed to find the local authority nodes!");
    }

    // Set the total value from the results
    CTDVString sCount = SP.GetIntField("Count");
    SetAttribute("NOTICEBOARDLIST","TOTAL",sCount);

    // Setup some local variables
    CTDVString sClubInfo;
    CTDVString sArticleInfo;
    CTDVString sDisplayName;
    CTDVString sSkip = iSkip;
    CTDVString sShow = iShow;
    SetAttribute("NOTICEBOARDLIST","SKIP",sSkip);
    SetAttribute("NOTICEBOARDLIST","SHOW",sShow);

    // Check to see if we're in a local authority area or higher?
    // Are we inside?
    CNotice Notice(m_InputContext);
    bool bOk = true;

    // Setup a counter to count down the number of results to show
    int iCount = iShow;
    int iAreaNode = 0;
    while (!SP.IsEOF() && iCount > 0 && bOk)
    {
        // Get the current nodeid, ArticleMembers, ClubMembers and DisplayName
        iAreaNode = SP.GetIntField("NodeID");
        SP.GetField("ArticleMembers",sArticleInfo);
        SP.GetField("ClubMembers",sClubInfo);
        SP.GetField("DisplayName",sDisplayName);

        // Get the noticeboard for the location
        if (Notice.GetNoticeBoardForNode(iAreaNode,iSiteID,false))
        {
            // Add the club and article info
            Notice.SetAttribute("NOTICEBOARD","LOCALAUTHORITY",sDisplayName);
            Notice.SetAttribute("NOTICEBOARD","ARTICLEMEMBERS",sArticleInfo);
            Notice.SetAttribute("NOTICEBOARD","CLUBMEMBERS",sClubInfo);

            bOk = AddInside("NOTICEBOARDLIST",&Notice);
            if (!bOk)
            {
                SetDNALastError("CNoticeBoardList","FailedInsertingNoticeINtoPage","Failed to insert noticeboard into XML Page!");
            }
        }

        // Get the next result
        SP.MoveNext();
        iCount--;
    }

    return bOk;
}
Ejemplo n.º 25
0
bool CUserPageBuilder::Build(CWholePage* pWholePage)
{
	// introducing the players - these will point to the XML objects required
	// to construct a user page
	CPageUI			Interface(m_InputContext);
	CUser*			pViewer = NULL;
	CUser			Owner(m_InputContext);
	CGuideEntry		Masthead(m_InputContext);
	CForum			PageForum(m_InputContext);
	CForum			Journal(m_InputContext);
	CPostList		RecentPosts(m_InputContext);
	CArticleList	RecentArticles(m_InputContext);
	CArticleList	RecentApprovals(m_InputContext);
	CCommentsList	RecentComments(m_InputContext);
	CArticleSubscriptionList	SubscribedUsersArticles(m_InputContext);
	
	CTDVString	sSecretKey;
	int			iSecretKey = 0;
	int			iUserID = 0;		// the user ID in the URL
	bool		bRegistering = false;
	bool		bSuccess = true;	// our success flag

	// get the user ID from the URL => zero if not present
	// TODO: something appropriate if no ID provided	
	iUserID = m_InputContext.GetParamInt("UserID");
	// now get the secret key if there is one
	// we may need to process it so get it as a string
	if (m_InputContext.GetParamString("Key", sSecretKey))
	{
		// if the secret key start with "3D" we must strip this off
		// - it is caused by a mime encoding problem, 3D is the ascii hex for =
		if (sSecretKey.Find("3D") == 0)
		{
			sSecretKey =  sSecretKey.Mid(2);
		}
		iSecretKey = atoi(sSecretKey);
		if (iSecretKey > 0)
		{
			// if there is a secret key then it is a registration attempt
			bRegistering = true;
		}
	}
	// now give appropriate page depending on whether this is a registration or not
	if (bRegistering)
	{
//		CStoredProcedure* pSP = m_InputContext.CreateStoredProcedureObject();
		CTDVString sPageContent = "";
		CTDVString sPageSubject = "";
//		CTDVString sCookie;

		// check we got our SP okay
//		if (pSP == NULL)
//		{
//			bSuccess = false;
//		}
		// if so then call the activate user method, which should return us a nice
		// warm cookie if all goes well
//		if (bSuccess)
//		{
//			bSuccess = pSP->ActivateUser(iUserID, iSecretKey, &sCookie);
			// make sure cookie is not empty
//			if (sCookie.IsEmpty())
//			{
//				bSuccess = false;
//			}
//		}
		// if okay then build page with the cookie in and a message to the user
		if (bSuccess)
		{
			// we have a cookie and we are prepared to use it
			// TODO: what about the MEMORY tag?
			// TODO: put this in stylesheet? Deal with delayed refresh?
//			CTDVString sCookieXML = "<SETCOOKIE><COOKIE>" + sCookie + "</COOKIE></SETCOOKIE>";

//			sPageSubject = "Registration in process ...";
//			sPageContent << "<GUIDE><BODY>";
//			sPageContent << "<P>Thank you for registering as an official Researcher for The Hitch Hiker's ";
//			sPageContent << "Guide to the Galaxy: we do hope you enjoy contributing to the Guide.</P>";
//			sPageContent << "<P>Please wait while you are transferred to <LINK BIO=\"U" << iUserID << "\">";
//			sPageContent << "your Personal Home Page</LINK> ... or click the link if nothing happens.</P>";
//			sPageContent << "</BODY></GUIDE>";
//			pWholePage = CreateSimplePage(sPageSubject, sPageContent);
//			if (pWholePage == NULL)
//			{
//				bSuccess = false;
//			}

			if (bSuccess)
			{
				bSuccess = InitPage(pWholePage, "USERPAGE",false);
			}
			// put the cookie xml inside the H2G2 tag
//			bSuccess = pWholePage->AddInside("H2G2", sCookieXML);

//			CTDVString sUserXML = "";
//			sUserXML << "<REGISTERING-USER>";
//			sUserXML << "<USER>";
//			sUserXML << "<USERNAME></USERNAME>";
//			sUserXML << "<USERID>" << iUserID << "</USERID>";
//			sUserXML << "</USER>";
//			sUserXML << "</REGISTERING-USER>";
//			bSuccess = pWholePage->AddInside("H2G2", sUserXML);
//			bSuccess = bSuccess && pWholePage->SetPageType("REGISTER-CONFIRMATION");

		CTDVString sRedirect;
		sRedirect << "ShowTerms" << iUserID;
		sRedirect << "?key=" << sSecretKey;
		pWholePage->Redirect(sRedirect);
		}
		else
		{
			sPageSubject = "Sorry ...";
			sPageContent << "<GUIDE><BODY>";
			sPageContent << "<P>The URL you've given is wrong. Please re-check your email, or <LINK HREF=\"/Register\">click here to re-enter your email address</LINK>.</P>";
			sPageContent << "</BODY></GUIDE>";
			bSuccess = CreateSimplePage(pWholePage, sPageSubject, sPageContent);
		}
		// make sure we delete the SP if any
//		delete pSP;
//		pSP = NULL;
	}
	else
	{
		// get or create all the appropriate xml objects
		pViewer		= m_InputContext.GetCurrentUser();
		bool bGotMasthead = false; 
		bool bGotPageForum = false; 
		bool bGotJournal = false; 
		bool bGotRecentPosts = false; 
		bool bGotRecentArticles = false; 
		bool bGotRecentApprovals = false; 
		bool bGotRecentComments = false; 
		bool bGotSubscribedToUsersRecentArticles = false; 

		bool bGotOwner		= CreatePageOwner(iUserID, Owner);

		CreatePageTemplate(pWholePage);
		if (m_InputContext.IncludeUsersGuideEntryInPersonalSpace() || (m_InputContext.GetParamInt("i_uge") == 1) ||
			m_InputContext.IncludeUsersGuideEntryForumInPersonalSpace() || (m_InputContext.GetParamInt("i_ugef") == 1))
		{
			bGotMasthead = CreatePageArticle(iUserID, Owner, Masthead);

			if (m_InputContext.IncludeUsersGuideEntryForumInPersonalSpace() || (m_InputContext.GetParamInt("i_ugef") == 1))
			{
				// GuideEntry forum can not be returned if GuideEntry is not being returned.
				bGotPageForum = CreatePageForum(pViewer, Masthead, PageForum);
			}
		}

		bool bGotInterface = CreateUserInterface(pViewer, Owner, Masthead, Interface);
		
		// Only display other information if the page has a valid masthead
		if (bGotMasthead)
		{
			if (m_InputContext.IncludeJournalInPersonalSpace() || (m_InputContext.GetParamInt("i_j") == 1))
			{
				bGotJournal = CreateJournal(Owner, pViewer, Journal);
			}

			if (m_InputContext.IncludeRecentPostsInPersonalSpace() || (m_InputContext.GetParamInt("i_rp") == 1))
			{
				bGotRecentPosts = CreateRecentPosts(Owner, pViewer, RecentPosts);
			}

			if (m_InputContext.IncludeRecentCommentsInPersonalSpace() || (m_InputContext.GetParamInt("i_rc") == 1))
			{
				bGotRecentComments = CreateRecentComments(Owner, pViewer, RecentComments);
			}

			if (m_InputContext.IncludeRecentGuideEntriesInPersonalSpace() || (m_InputContext.GetParamInt("i_rge") == 1))
			{
				bGotRecentArticles = CreateRecentArticles(Owner, RecentArticles);
				bGotRecentApprovals = CreateRecentApprovedArticles(Owner, RecentApprovals);
			}

			if (m_InputContext.IncludeUploadsInPersonalSpace() || (m_InputContext.GetParamInt("i_u") == 1))
			{
				CTDVString sUploadsXML;
				CUpload Upload(m_InputContext);
				Upload.GetUploadsForUser(iUserID,sUploadsXML);
				pWholePage->AddInside("H2G2",sUploadsXML);
			}

			if (m_InputContext.IncludeRecentArticlesOfSubscribedToUsersInPersonalSpace() || (m_InputContext.GetParamInt("i_rasu") == 1))
			{
				bGotSubscribedToUsersRecentArticles = CreateSubscribedToUsersRecentArticles(Owner, m_InputContext.GetSiteID(), SubscribedUsersArticles); 
			}
		}

		// See if the user wants to swap to this site and change their masthead and journal (if it exists)
/*
	This feature is now redundant. There's no concept of a homesite.
		if (m_InputContext.ParamExists("homesite"))
		{
			if (pViewer == NULL)
			{
				// error: Not registered - ignore request
			}
			else if (!bGotOwner)
			{
				// error - no actual owner, ignore request
			}
			else if (pViewer->GetIsEditor())
			{
				int iCurrentSiteID = m_InputContext.GetSiteID();
				int iThisSite = iCurrentSiteID;
				if (bGotMasthead)
				{
					iCurrentSiteID = Masthead.GetSiteID();
				}
				if ( iThisSite != iCurrentSiteID && m_InputContext.CanUserMoveToSite(iCurrentSiteID, iThisSite))
				{
					CStoredProcedure SP;
					m_InputContext.InitialiseStoredProcedureObject(&SP);
					if (bGotMasthead)
					{
						SP.MoveArticleToSite(Masthead.GetH2G2ID(), m_InputContext.GetSiteID());
						//delete pMasthead;
						Masthead.Destroy();
						bGotMasthead = CreatePageArticle(iUserID, Owner, Masthead);
					}
					int iJournal;
					Owner.GetJournal(&iJournal);
					if (iJournal > 0)
					{
						SP.MoveForumToSite(iJournal, m_InputContext.GetSiteID());
					}

					int iPrivateForum;
					if (Owner.GetPrivateForum(&iPrivateForum))
					{
						SP.MoveForumToSite(iPrivateForum, m_InputContext.GetSiteID());
					}
					pWholePage->AddInside("H2G2", "<SITEMOVED RESULT='success'/>");
				}
			}
		}
*/
		// check that all the *required* objects have been created successfully
		// note that pViewer can be NULL if an unregistered viewer
		// pOwner can be NULL if we are serving a default page because this user ID
		// does not exist
		// bGotJournal can be false if the user doesn't exist, or has no journal
		// bGotRecentPosts can be false if the user doesn't exist
		// pRecentArticles can be NULL if the user doesn't exist
		// pRecentApprovals can be NULL if the user doesn't exist
		// bGotPageForum can be false if there is no masthead, or if it has no forum yet
		// pMasthead could be NULL if the user has not created one yet
		if (pWholePage->IsEmpty() || bGotInterface == false)
		{
			bSuccess = false;
		}
		// now add all the various subcomponents into the whole page xml
		// add owner of page
		if (bSuccess)
		{
			// if we have a page owner then put their details in, otherwise make
			// up a pretend user from the ID we were given
			if (bGotOwner)
			{
				bSuccess = pWholePage->AddInside("PAGE-OWNER", &Owner);
			}
			else
			{
				CTDVString sPretendUserXML = "";
				sPretendUserXML << "<USER><USERID>" << iUserID << "</USERID>";
				sPretendUserXML << "<USERNAME>Researcher " << iUserID << "</USERNAME></USER>";
				bSuccess = pWholePage->AddInside("PAGE-OWNER", sPretendUserXML);
			}
		}
		// there should always be an interface but check anyway
		if (bSuccess && bGotInterface)
		{
			bSuccess = pWholePage->AddInside("H2G2", &Interface);
		}
		if (bSuccess && m_InputContext.ParamExists("clip"))
		{
			CTDVString sSubject;
			if (bGotOwner)
			{
				Owner.GetUsername(sSubject);
			}
			else
			{
				sSubject << "U" << iUserID;
			}

			bool bPrivate = m_InputContext.GetParamInt("private") > 0;
			CLink Link(m_InputContext);
			if ( Link.ClipPageToUserPage("userpage", iUserID, sSubject, NULL, pViewer, bPrivate) )
				pWholePage->AddInside("H2G2", &Link);
		}
		// if masthead NULL stylesheet should do the default response
		if (bSuccess && bGotMasthead && (m_InputContext.IncludeUsersGuideEntryInPersonalSpace() || (m_InputContext.GetParamInt("i_uge") == 1)))
		{
			bSuccess = pWholePage->AddInside("H2G2", &Masthead);
		}
		// add page forum if there is one => this is the forum associated with
		// the guide enty that is the masthead for this user
		if (bSuccess && bGotPageForum && (m_InputContext.IncludeUsersGuideEntryForumInPersonalSpace() || (m_InputContext.GetParamInt("i_ugef") == 1)))
		{
			bSuccess = pWholePage->AddInside("H2G2", &PageForum);
		}
		// add journal if it exists
		if (bSuccess && bGotJournal)
		{
			bSuccess = pWholePage->AddInside("JOURNAL", &Journal);
		}
		// add recent posts if they exist, this may add an empty
		// POST-LIST tag if the user exists but has never posted
		if (bSuccess && bGotRecentPosts)
		{
			bSuccess = pWholePage->AddInside("RECENT-POSTS", &RecentPosts);
		}
		// add recent articles if they exist, this may add an empty
		// ARTICLES-LIST tag if the user exists but has never written a guide entry
		if (bSuccess && bGotRecentArticles)
		{
			bSuccess = pWholePage->AddInside("RECENT-ENTRIES", &RecentArticles);
			// add the user XML for the owner too
			if (bGotOwner)
			{
				bSuccess = bSuccess && pWholePage->AddInside("RECENT-ENTRIES", &Owner);
			}
		}
		// add recent articles if they exist, this may add an empty
		// ARTICLES-LIST tag if the user exists but has never had an entry approved
		if (bSuccess && bGotRecentApprovals)
		{
			bSuccess = pWholePage->AddInside("RECENT-APPROVALS", &RecentApprovals);
			// add the user XML for the owner too
			if (bGotOwner)
			{
				bSuccess = bSuccess && pWholePage->AddInside("RECENT-APPROVALS", &Owner);
			}
		}
		// add recent comments if they exist, this may add an empty
		// COMMENTS-LIST tag if the user exists but has never posted
		if (bSuccess && bGotRecentComments)
		{
			bSuccess = pWholePage->AddInside("RECENT-COMMENTS", &RecentComments);
		}

		if (bSuccess && bGotSubscribedToUsersRecentArticles)
		{
			bSuccess = pWholePage->AddInside("RECENT-SUBSCRIBEDARTICLES", &SubscribedUsersArticles);
		}

		CTDVString sSiteXML;
		m_InputContext.GetSiteListAsXML(&sSiteXML);
		bSuccess = bSuccess && pWholePage->AddInside("H2G2", sSiteXML);

		if (bGotMasthead && (m_InputContext.IncludeWatchInfoInPersonalSpace() || (m_InputContext.GetParamInt("i_wi") == 1)))
		{
			CWatchList WatchList(m_InputContext);
			bSuccess = bSuccess && WatchList.Initialise(iUserID);
			bSuccess = bSuccess && pWholePage->AddInside("H2G2",&WatchList);
			int iSiteID = m_InputContext.GetSiteID();
			bSuccess = bSuccess && WatchList.WatchingUsers(iUserID, iSiteID);
			bSuccess = bSuccess && pWholePage->AddInside("H2G2",&WatchList);
		}

		CWhosOnlineObject Online(m_InputContext);
		bSuccess = bSuccess && Online.Initialise(NULL, 1, true);
		bSuccess = bSuccess && pWholePage->AddInside("H2G2", &Online);

		if (bGotMasthead && (m_InputContext.IncludeClubsInPersonalSpace() || (m_InputContext.GetParamInt("i_c") == 1)))
		{
			if (pViewer != NULL && pViewer->GetUserID() == iUserID) 
			{
				CClub Club(m_InputContext);
				Club.GetUserActionList(iUserID, 0, 20);
				pWholePage->AddInside("H2G2", &Club);
			}

			// Now add all the clubs the user belongs to
			CCurrentClubs Clubs(m_InputContext);
			if (bSuccess && Clubs.CreateList(iUserID,true))
			{
				bSuccess = pWholePage->AddInside("H2G2",&Clubs);
			}
		}
		
		if (bGotMasthead && bSuccess && (m_InputContext.IncludePrivateForumsInPersonalSpace() || (m_InputContext.GetParamInt("i_pf") == 1)))
		{
			pWholePage->AddInside("H2G2", "<PRIVATEFORUM/>");
			CForum Forum(m_InputContext);
			int iPrivateForum = 0;
			if (bGotOwner)
			{
				Owner.GetPrivateForum(&iPrivateForum);
			}
			Forum.GetThreadList(pViewer, iPrivateForum, 10,0);
			pWholePage->AddInside("PRIVATEFORUM", &Forum);

			// Now check to see if the user has alerts set for their private forum
			if (bGotOwner)
			{
				CEmailAlertList Alert(m_InputContext);
				Alert.GetUserEMailAlertSubscriptionForForumAndThreads(iUserID,iPrivateForum);
				pWholePage->AddInside("PRIVATEFORUM", &Alert);
			}
		}

		if (bGotMasthead && bSuccess && (m_InputContext.IncludeLinksInPersonalSpace() || (m_InputContext.GetParamInt("i_l") == 1)))
		{
			CTDVString sLinkGroup;
			m_InputContext.GetParamString("linkgroup", sLinkGroup);
			if (bGotOwner && pViewer != NULL && Owner.GetUserID() == pViewer->GetUserID()) 
			{
				ManageClippedLinks(pWholePage);
			}
			if (bGotOwner)
			{
				CLink Link(m_InputContext);
				bool bShowPrivate = (pViewer != NULL && Owner.GetUserID() == pViewer->GetUserID());
				Link.GetUserLinks(Owner.GetUserID(), sLinkGroup, bShowPrivate);
				pWholePage->AddInside("H2G2", &Link);
				Link.GetUserLinkGroups(Owner.GetUserID());
				pWholePage->AddInside("H2G2", &Link);
			}
		}

		if (bGotMasthead && m_InputContext.IncludeTaggedNodesInPersonalSpace() || (m_InputContext.GetParamInt("i_tn") == 1))
		{
			//Get the Users Crumtrail - all the nodes + ancestors the user is tagged to .
			CCategory CCat(m_InputContext);
			if ( bSuccess && CCat.GetUserCrumbTrail(Owner.GetUserID()) )
			{
				bSuccess = pWholePage->AddInside("H2G2",&CCat);
			}
		}

		if (bSuccess && bGotMasthead)
		{
			CTDVString sPostCodeXML;
			CTDVString sNoticeXML;
			if (m_InputContext.IncludeNoticeboardInPersonalSpace() || (m_InputContext.GetParamInt("i_n") == 1) ||
				m_InputContext.IncludePostcoderInPersonalSpace() || (m_InputContext.GetParamInt("i_p") == 1))
			{
				if (pViewer != NULL)
				{
					// Insert the notice board information!
					CTDVString sPostCodeToFind;
					if(pViewer->GetPostcode(sPostCodeToFind))
					{
						int iSiteID = m_InputContext.GetSiteID();
						CNotice Notice(m_InputContext);
						if (!Notice.GetLocalNoticeBoardForPostCode(sPostCodeToFind,iSiteID,sNoticeXML,sPostCodeXML))
						{
							sNoticeXML << "<NOTICEBOARD><ERROR>FailedToFindLocalNoticeBoard</ERROR></NOTICEBOARD>";
						}
					}
					else
					{
						//if the user has not entered a postcode then flag an Notice Board error
						sNoticeXML << "<NOTICEBOARD><ERROR>UserNotEnteredPostCode</ERROR></NOTICEBOARD>";
					}
				}
				else
				{
					sNoticeXML << "<NOTICEBOARD><ERROR>UserNotLoggedIn</ERROR></NOTICEBOARD>";
				}

				if (m_InputContext.IncludeNoticeboardInPersonalSpace() || (m_InputContext.GetParamInt("i_n") == 1))
				{
					bSuccess = pWholePage->AddInside("H2G2",sNoticeXML);
				}
			}

			if (m_InputContext.IncludePostcoderInPersonalSpace() || (m_InputContext.GetParamInt("i_p") == 1))
			{
				// Insert the postcoder if it's not empty
				if (bSuccess && !sPostCodeXML.IsEmpty())
				{
					bSuccess = bSuccess && pWholePage->AddInside("H2G2",sPostCodeXML);
				}
			}
		}

		if (m_InputContext.IncludeSiteOptionsInPersonalSpace() || (m_InputContext.GetParamInt("i_so") == 1))
		{
			// Return SiteOption SystemMessageOn if set. 
			if (bSuccess && m_InputContext.IsSystemMessagesOn(m_InputContext.GetSiteID()))
			{
				CTDVString sSiteOptionSystemMessageXML = "<SITEOPTION><NAME>UseSystemMessages</NAME><VALUE>1</VALUE></SITEOPTION>"; 

				bSuccess = bSuccess && pWholePage->AddInside("H2G2",sSiteOptionSystemMessageXML);
			}
		}
		
/*
		Mark Howitt 11/8/05 - Removing the civic data from the user page as it is nolonger used by any sites.
							  The only place civic data is used now is on the postcoder page.

		//include civic data
		if (bSuccess)
		{
			if ( m_InputContext.GetSiteID( ) == 16 )
			{
				CTDVString sActualPostCode;				
				bool bFoundLocalInfo = false;
				// First check to see if there is a postcode in the URL
				if (m_InputContext.ParamExists("postcode"))
				{
					// Get the postcode and use this to display the noticeboard
					if (m_InputContext.GetParamString("postcode", sActualPostCode))
					{
						//dont do any validations
						bFoundLocalInfo = true;				
					}
				}

				//next if no postcode variable is included in URL
				//or if the specified postcode value is invalid 
				//or if the specified postcode value has no entries on the db				
				if (!bFoundLocalInfo)
				{
					// No postcode given, try to get the viewing users postcode if we have one.
					if (pViewer)
					{
						if (pViewer->GetPostcode(sActualPostCode))
						{
							if ( sActualPostCode.IsEmpty( ) == false)
							{
								//dont do any validations
								bFoundLocalInfo = true;
							}
						}							
					}
					else
					{
						//try session cookie, if any 
						CTDVString sPostCodeToFind;
						CPostcoder postcoder(m_InputContext);
						CTDVString sActualPostCode = postcoder.GetPostcodeFromCookie();
						if ( !sActualPostCode.IsEmpty() )
						{
							//dont do any validations
							bFoundLocalInfo = true;
						}
					}
				}

				if ( bFoundLocalInfo )
				{
					if (!sActualPostCode.IsEmpty())
					{
						bool bHitPostcode = false;
						CPostcoder cPostcoder(m_InputContext);
						cPostcoder.MakePlaceRequest(sActualPostCode, bHitPostcode);
						if (bHitPostcode)
						{
							CTDVString sXML = "<CIVICDATA POSTCODE='";
							sXML << sActualPostCode << "'/>";
							pWholePage->AddInside("H2G2", sXML);
							bSuccess = pWholePage->AddInside("CIVICDATA",&cPostcoder);
						}
					}
				}
			}
		}
*/
	}

	return bSuccess;
}
Ejemplo n.º 26
0
bool CNoticeBoardList::GetAllNoticeBoards(CWholePage* pPage, const int iSiteID, int iSkip, int iShow)
{
    // Check to make sure we've been given a valid page to play with
    if (pPage == NULL)
    {
        return SetDNALastError("CNoticeBoardList","NULLPageObjectGiven","No page given to fill in!!!");
    }

    // Now get the all the noticeboards from the taxonomy
    CStoredProcedure SP;
    m_InputContext.InitialiseStoredProcedureObject(&SP);
    if (!SP.GetAllLocalAuthorityNodes(iSiteID,0,5))
    {
        return SetDNALastError("CNoticeBoardList","FailedToGetNodes","Failed to find the local authority nodes!");
    }

    // Now go through all the nodes getting the localnoticeboard info
    // Setup some local variables
    CTDVString sXML;
    bool bOk = true;
    CNotice Notice(m_InputContext);
    CTDVString sClubInfo;
    CTDVString sArticleInfo;
    CTDVString sDisplayName;
    int iNodeID = 0;

    // Check to see if we've been asked to skip
    if (iSkip > 0)
    {
        SP.MoveNext(iSkip);
    }

    // Put the skip, show and total count into the page
    CTDVString sSkip = iSkip;
    CTDVString sShow = iShow;
    CTDVString sCount = SP.GetIntField("Count");
    pPage->SetAttribute("NOTICEBOARDLIST","SKIP",sSkip);
    pPage->SetAttribute("NOTICEBOARDLIST","SHOW",sShow);
    pPage->SetAttribute("NOTICEBOARDLIST","TOTAL",sCount);

    // Setup a counter to count down the number of results to show
    int iCount = iShow;
    while (!SP.IsEOF() && iCount > 0 && bOk)
    {
        // Get the current nodeid, ArticleMembers, ClubMembers and DisplayName
        iNodeID = SP.GetIntField("NodeID");
        SP.GetField("ArticleMembers",sArticleInfo);
        SP.GetField("ClubMembers",sClubInfo);
        SP.GetField("DisplayName",sDisplayName);

        // Get the noticeboard for the location
        if (Notice.GetNoticeBoardForNode(iNodeID,iSiteID))
        {
            // Add the club and article info
            Notice.SetAttribute("NOTICEBOARD","LOCALAUTHORITY",sDisplayName);
            Notice.SetAttribute("NOTICEBOARD","ARTICLEMEMBERS",sArticleInfo);
            Notice.SetAttribute("NOTICEBOARD","CLUBMEMBERS",sClubInfo);

            bOk = pPage->AddInside("NOTICEBOARDLIST",&Notice);
            if (!bOk)
            {
                SetDNALastError("CNoticeBoardList","FailedInsertingNoticeINtoPage","Failed to insert noticeboard into XML Page!");
            }
        }

        // Get the next result
        SP.MoveNext();
        iCount--;
    }

    // Return the verdict
    return bOk;
}
Ejemplo n.º 27
0
    Shape *MakeLoop(BlockSet &Blocks, BlockSet& Entries, BlockSet &NextEntries) {
      // Find the inner blocks in this loop. Proceed backwards from the entries until
      // you reach a seen block, collecting as you go.
      BlockSet InnerBlocks;
      BlockSet Queue = Entries;
      while (Queue.size() > 0) {
        Block *Curr = *(Queue.begin());
        Queue.erase(Queue.begin());
        if (!contains(InnerBlocks, Curr)) {
          // This element is new, mark it as inner and remove from outer
          InnerBlocks.insert(Curr);
          Blocks.erase(Curr);
          // Add the elements prior to it
          for (BlockSet::iterator iter = Curr->BranchesIn.begin(); iter != Curr->BranchesIn.end(); iter++) {
            Queue.insert(*iter);
          }
#if 0
          // Add elements it leads to, if they are dead ends. There is no reason not to hoist dead ends
          // into loops, as it can avoid multiple entries after the loop
          for (BlockBranchMap::iterator iter = Curr->BranchesOut.begin(); iter != Curr->BranchesOut.end(); iter++) {
            Block *Target = iter->first;
            if (Target->BranchesIn.size() <= 1 && Target->BranchesOut.size() == 0) {
              Queue.insert(Target);
            }
          }
#endif
        }
      }
      assert(InnerBlocks.size() > 0);

      for (BlockSet::iterator iter = InnerBlocks.begin(); iter != InnerBlocks.end(); iter++) {
        Block *Curr = *iter;
        for (BlockBranchMap::iterator iter = Curr->BranchesOut.begin(); iter != Curr->BranchesOut.end(); iter++) {
          Block *Possible = iter->first;
          if (!contains(InnerBlocks, Possible)) {
            NextEntries.insert(Possible);
          }
        }
      }

#if 0
      // We can avoid multiple next entries by hoisting them into the loop.
      if (NextEntries.size() > 1) {
        BlockBlockSetMap IndependentGroups;
        FindIndependentGroups(NextEntries, IndependentGroups, &InnerBlocks);

        while (IndependentGroups.size() > 0 && NextEntries.size() > 1) {
          Block *Min = NULL;
          int MinSize = 0;
          for (BlockBlockSetMap::iterator iter = IndependentGroups.begin(); iter != IndependentGroups.end(); iter++) {
            Block *Entry = iter->first;
            BlockSet &Blocks = iter->second;
            if (!Min || Blocks.size() < MinSize) { // TODO: code size, not # of blocks
              Min = Entry;
              MinSize = Blocks.size();
            }
          }
          // check how many new entries this would cause
          BlockSet &Hoisted = IndependentGroups[Min];
          bool abort = false;
          for (BlockSet::iterator iter = Hoisted.begin(); iter != Hoisted.end() && !abort; iter++) {
            Block *Curr = *iter;
            for (BlockBranchMap::iterator iter = Curr->BranchesOut.begin(); iter != Curr->BranchesOut.end(); iter++) {
              Block *Target = iter->first;
              if (Hoisted.find(Target) == Hoisted.end() && NextEntries.find(Target) == NextEntries.end()) {
                // abort this hoisting
                abort = true;
                break;
              }
            }
          }
          if (abort) {
            IndependentGroups.erase(Min);
            continue;
          }
          // hoist this entry
          PrintDebug("hoisting %d into loop\n", Min->Id);
          NextEntries.erase(Min);
          for (BlockSet::iterator iter = Hoisted.begin(); iter != Hoisted.end(); iter++) {
            Block *Curr = *iter;
            InnerBlocks.insert(Curr);
            Blocks.erase(Curr);
          }
          IndependentGroups.erase(Min);
        }
      }
#endif

      PrintDebug("creating loop block:\n");
      DebugDump(InnerBlocks, "  inner blocks:");
      DebugDump(Entries, "  inner entries:");
      DebugDump(Blocks, "  outer blocks:");
      DebugDump(NextEntries, "  outer entries:");

      LoopShape *Loop = new LoopShape();
      Notice(Loop);

      // Solipsize the loop, replacing with break/continue and marking branches as Processed (will not affect later calculations)
      // A. Branches to the loop entries become a continue to this shape
      for (BlockSet::iterator iter = Entries.begin(); iter != Entries.end(); iter++) {
        Solipsize(*iter, Branch::Continue, Loop, InnerBlocks);
      }
      // B. Branches to outside the loop (a next entry) become breaks on this shape
      for (BlockSet::iterator iter = NextEntries.begin(); iter != NextEntries.end(); iter++) {
        Solipsize(*iter, Branch::Break, Loop, InnerBlocks);
      }
      // Finish up
      Shape *Inner = Process(InnerBlocks, Entries, NULL);
      Loop->Inner = Inner;
      return Loop;
    }
Ejemplo n.º 28
0
/* perform socks4 client dialog on existing FD.
   Called within fork/retry loop, after connect() */
int _xioopen_socks4_connect(struct single *xfd,
                            struct socks4 *sockhead,
                            size_t headlen,
                            int level) {
    ssize_t bytes;
    int result;
    unsigned char buff[SIZEOF_STRUCT_SOCKS4];
    struct socks4 *replyhead = (struct socks4 *)buff;
    char *destdomname = NULL;

    /* send socks header (target addr+port, +auth) */
#if WITH_MSGLEVEL <= E_INFO
    if (ntohl(sockhead->dest) <= 0x000000ff) {
        destdomname = strchr(sockhead->userid, '\0')+1;
    }
    Info11("sending socks4%s request VN=%d DC=%d DSTPORT=%d DSTIP=%d.%d.%d.%d USERID=%s%s%s",
           destdomname?"a":"",
           sockhead->version, sockhead->action, ntohs(sockhead->port),
           ((unsigned char *)&sockhead->dest)[0],
           ((unsigned char *)&sockhead->dest)[1],
           ((unsigned char *)&sockhead->dest)[2],
           ((unsigned char *)&sockhead->dest)[3],
           sockhead->userid,
           destdomname?" DESTNAME=":"",
           destdomname?destdomname:"");
#endif /* WITH_MSGLEVEL <= E_INFO */
#if WITH_MSGLEVEL <= E_DEBUG
    {
        char *msgbuff;
        if ((msgbuff = Malloc(3*headlen)) != NULL) {
            xiohexdump((const unsigned char *)sockhead, headlen, msgbuff);
            Debug1("sending socks4(a) request data %s", msgbuff);
        }
    }
#endif /* WITH_MSGLEVEL <= E_DEBUG */
    if (writefull(xfd->fd, sockhead, headlen) < 0) {
        Msg4(level, "write(%d, %p, "F_Zu"): %s",
             xfd->fd, sockhead, headlen, strerror(errno));
        if (Close(xfd->fd) < 0) {
            Info2("close(%d): %s", xfd->fd, strerror(errno));
        }
        return STAT_RETRYLATER;	/* retry complete open cycle */
    }

    bytes = 0;
    Info("waiting for socks reply");
    while (bytes >= 0) {	/* loop over answer chunks until complete or error */
        /* receive socks answer */
        do {
            result = Read(xfd->fd, buff+bytes, SIZEOF_STRUCT_SOCKS4-bytes);
        } while (result < 0 && errno == EINTR);
        if (result < 0) {
            Msg4(level, "read(%d, %p, "F_Zu"): %s",
                 xfd->fd, buff+bytes, SIZEOF_STRUCT_SOCKS4-bytes,
                 strerror(errno));
            if (Close(xfd->fd) < 0) {
                Info2("close(%d): %s", xfd->fd, strerror(errno));
            }
        }
        if (result == 0) {
            Msg(level, "read(): EOF during read of socks reply, peer might not be a socks4 server");
            if (Close(xfd->fd) < 0) {
                Info2("close(%d): %s", xfd->fd, strerror(errno));
            }
            return STAT_RETRYLATER;
        }
#if WITH_MSGLEVEL <= E_DEBUG
        {
            char msgbuff[3*SIZEOF_STRUCT_SOCKS4];
            * xiohexdump((const unsigned char *)replyhead+bytes, result, msgbuff)
                = '\0';
            Debug2("received socks4 reply data (offset "F_Zd"): %s", bytes, msgbuff);
        }
#endif /* WITH_MSGLEVEL <= E_DEBUG */
        bytes += result;
        if (bytes == SIZEOF_STRUCT_SOCKS4) {
            Debug1("received all "F_Zd" bytes", bytes);
            break;
        }
        Debug2("received %d bytes, waiting for "F_Zu" more bytes",
               result, SIZEOF_STRUCT_SOCKS4-bytes);
    }
    if (result <= 0) {	/* we had a problem while reading socks answer */
        return STAT_RETRYLATER;	/* retry complete open cycle */
    }

    Info7("received socks reply VN=%u CD=%u DSTPORT=%u DSTIP=%u.%u.%u.%u",
          replyhead->version, replyhead->action, ntohs(replyhead->port),
          ((uint8_t *)&replyhead->dest)[0],
          ((uint8_t *)&replyhead->dest)[1],
          ((uint8_t *)&replyhead->dest)[2],
          ((uint8_t *)&replyhead->dest)[3]);
    if (replyhead->version != 0) {
        Warn1("socks: reply code version is not 0 (%d)",
              replyhead->version);
    }

    switch (replyhead->action) {
    case SOCKS_CD_GRANTED:
        /* Notice("socks: connect request succeeded"); */
#if 0
        if (Getsockname(xfd->fd, (struct sockaddr *)&us, &uslen) < 0) {
            Warn4("getsockname(%d, %p, {%d}): %s",
                  xfd->fd, &us, uslen, strerror(errno));
        }
        Notice1("successfully connected from %s via socks4",
                sockaddr_info((struct sockaddr *)&us, infobuff, sizeof(infobuff)));
#else
        Notice("successfully connected via socks4");
#endif
        break;

    case SOCKS_CD_FAILED:
        Msg(level, "socks: connect request rejected or failed");
        return STAT_RETRYLATER;

    case SOCKS_CD_NOIDENT:
        Msg(level, "socks: ident refused by client");
        return STAT_RETRYLATER;

    case SOCKS_CD_IDENTFAILED:
        Msg(level, "socks: ident failed");
        return STAT_RETRYLATER;

    default:
        Msg1(level, "socks: undefined status %u", replyhead->action);
    }

    return STAT_OK;
}
Ejemplo n.º 29
0
static int xioopen_tun(int argc, const char *argv[], struct opt *opts, int xioflags, xiofile_t *xfd, unsigned groups, int dummy1, int dummy2, int dummy3) {
   char *tundevice = NULL;
   char *tunname = NULL, *tuntype = NULL;
   int pf = /*! PF_UNSPEC*/ PF_INET;
   struct xiorange network;
   bool no_pi = false;
   const char *namedargv[] = { "tun", NULL, NULL };
   int rw = (xioflags & XIO_ACCMODE);
   bool exists;
   struct ifreq ifr;
   int sockfd;
   char *ifaddr;
   int result;

   if (argc > 2 || argc < 0) {
      Error2("%s: wrong number of parameters (%d instead of 0 or 1)",
	     argv[0], argc-1);
   }

   if (retropt_string(opts, OPT_TUN_DEVICE, &tundevice) != 0) {
      tundevice = strdup("/dev/net/tun");
   }

   /*! socket option here? */
   retropt_socket_pf(opts, &pf);

   namedargv[1] = tundevice;
   /* open the tun cloning device */
   if ((result = _xioopen_named_early(2, namedargv, xfd, groups, &exists, opts)) < 0) {
      return result;
   }

   /*========================= the tunnel interface =========================*/
   Notice("creating tunnel network interface");
   if ((result = _xioopen_open(tundevice, rw, opts)) < 0)
      return result;
   xfd->stream.fd = result;

   /* prepare configuration of the new network interface */
   memset(&ifr, 0,sizeof(ifr));

   if (retropt_string(opts, OPT_TUN_NAME, &tunname) == 0) {
      strncpy(ifr.ifr_name, tunname, IFNAMSIZ);	/* ok */
      free(tunname);
   } else {
      ifr.ifr_name[0] = '\0';
   }

   ifr.ifr_flags = IFF_TUN;
   if (retropt_string(opts, OPT_TUN_TYPE, &tuntype) == 0) {
      if (!strcmp(tuntype, "tap")) {
	 ifr.ifr_flags = IFF_TAP;
      } else if (strcmp(tuntype, "tun")) {
	 Error1("unknown tun-type \"%s\"", tuntype);
      }
   }

   if (retropt_bool(opts, OPT_IFF_NO_PI, &no_pi) == 0) {
      if (no_pi) {
	 ifr.ifr_flags |= IFF_NO_PI;
#if 0 /* not neccessary for now */
      } else {
	 ifr.ifr_flags &= ~IFF_NO_PI;
#endif
      }
   }

   if (Ioctl(xfd->stream.fd, TUNSETIFF, &ifr) < 0) {
      Error3("ioctl(%d, TUNSETIFF, {\"%s\"}: %s",
	     xfd->stream.fd, ifr.ifr_name, strerror(errno));
      Close(xfd->stream.fd);
   }

   /*===================== setting interface properties =====================*/

   /* we seem to need a socket for manipulating the interface */
   if ((sockfd = Socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
      Error1("socket(PF_INET, SOCK_DGRAM, 0): %s", strerror(errno));
      sockfd = xfd->stream.fd;	/* desparate fallback attempt */
   }

   /*--------------------- setting interface address and netmask ------------*/
   if (argc == 2) {
       if ((ifaddr = strdup(argv[1])) == NULL) {
          Error1("strdup(\"%s\"): out of memory", argv[1]);
          return STAT_RETRYLATER;
       }
       if ((result = xioparsenetwork(ifaddr, pf, &network)) != STAT_OK) {
          /*! recover */
          return result;
       }
       socket_init(pf, (union sockaddr_union *)&ifr.ifr_addr);
       ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr =
          network.netaddr.ip4.sin_addr;
       if (Ioctl(sockfd, SIOCSIFADDR, &ifr) < 0) {
          Error4("ioctl(%d, SIOCSIFADDR, {\"%s\", \"%s\"}: %s",
             sockfd, ifr.ifr_name, ifaddr, strerror(errno));
       }
       ((struct sockaddr_in *)&ifr.ifr_netmask)->sin_addr =
          network.netmask.ip4.sin_addr;
       if (Ioctl(sockfd, SIOCSIFNETMASK, &ifr) < 0) {
          Error4("ioctl(%d, SIOCSIFNETMASK, {\"0x%08u\", \"%s\"}, %s",
             sockfd, ((struct sockaddr_in *)&ifr.ifr_netmask)->sin_addr.s_addr,
             ifaddr, strerror(errno));
       }
       free(ifaddr);
   }
   /*--------------------- setting interface flags --------------------------*/
   applyopts_single(&xfd->stream, opts, PH_FD);

   if (Ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
      Error3("ioctl(%d, SIOCGIFFLAGS, {\"%s\"}: %s",
	     sockfd, ifr.ifr_name, strerror(errno));
   }
   Debug2("\"%s\": system set flags: 0x%hx", ifr.ifr_name, ifr.ifr_flags);
   ifr.ifr_flags |= xfd->stream.para.tun.iff_opts[0];
   ifr.ifr_flags &= ~xfd->stream.para.tun.iff_opts[1];
   Debug2("\"%s\": xio merged flags: 0x%hx", ifr.ifr_name, ifr.ifr_flags);
   if (Ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
      Error4("ioctl(%d, SIOCSIFFLAGS, {\"%s\", %hd}: %s",
	     sockfd, ifr.ifr_name, ifr.ifr_flags, strerror(errno));
   }
   ifr.ifr_flags = 0;
   if (Ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
      Error3("ioctl(%d, SIOCGIFFLAGS, {\"%s\"}: %s",
	     sockfd, ifr.ifr_name, strerror(errno));
   }
   Debug2("\"%s\": resulting flags: 0x%hx", ifr.ifr_name, ifr.ifr_flags);


#if LATER
   applyopts_named(tundevice, opts, PH_FD);
#endif
   applyopts(xfd->stream.fd, opts, PH_FD);
   applyopts_cloexec(xfd->stream.fd, opts);

   applyopts_fchown(xfd->stream.fd, opts);

   if ((result = _xio_openlate(&xfd->stream, opts)) < 0)
      return result;

   return 0;
}
Ejemplo n.º 30
0
/* process a bidirectional "stdio" or "-" argument with options.
   generate a dual address. */
int xioopen_stdio_bi(xiofile_t *sock) {
   struct opt *optspr;
   unsigned int groups1 = addr_stdio.groups;
   int result;

   if (xioopen_makedual(sock) < 0) {
      return -1;
   }

   sock->dual.stream[0]->tag = XIO_TAG_RDONLY;
   sock->dual.stream[0]->fd = 0 /*stdin*/;
   sock->dual.stream[1]->tag = XIO_TAG_WRONLY;
   sock->dual.stream[1]->fd = 1 /*stdout*/;
   sock->dual.stream[0]->howtoend =
      sock->dual.stream[1]->howtoend = END_NONE;

#if WITH_TERMIOS
   if (Isatty(sock->dual.stream[0]->fd)) {
      if (Tcgetattr(sock->dual.stream[0]->fd,
		    &sock->dual.stream[0]->savetty)
	  < 0) {
	 Warn2("cannot query current terminal settings on fd %d: %s",
	       sock->dual.stream[0]->fd, strerror(errno));
      } else {
	 sock->dual.stream[0]->ttyvalid = true;
      }
   }
   if (Isatty(sock->dual.stream[1]->fd)) {
      if (Tcgetattr(sock->dual.stream[1]->fd,
		    &sock->dual.stream[1]->savetty)
	  < 0) {
	 Warn2("cannot query current terminal settings on fd %d: %s",
	       sock->dual.stream[1]->fd, strerror(errno));
      } else {
	 sock->dual.stream[1]->ttyvalid = true;
      }
   }
#endif /* WITH_TERMIOS */

   /* options here are one-time and one-direction, no second use */
   retropt_bool(sock->stream.opts, OPT_IGNOREEOF, &sock->dual.stream[0]->ignoreeof);

   /* extract opts that should be applied only once */
   if ((optspr = copyopts(sock->stream.opts, GROUP_PROCESS)) == NULL) {
      return -1;
   }
   /* here we copy opts, because most have to be applied twice! */
   if ((sock->dual.stream[1]->opts = copyopts(sock->stream.opts, GROUP_FD|GROUP_APPL|(groups1&~GROUP_PROCESS))) == NULL) {
      return -1;
   }
   sock->dual.stream[0]->opts = sock->stream.opts;
   sock->stream.opts = NULL;

   if (applyopts_single(sock->dual.stream[0],
			sock->dual.stream[0]->opts, PH_INIT)
       < 0)
      return -1;
   if (applyopts_single(sock->dual.stream[1],
			sock->dual.stream[1]->opts, PH_INIT)
       < 0)
      return -1;
   applyopts(-1, sock->dual.stream[0]->opts, PH_INIT);
   applyopts(-1, sock->dual.stream[1]->opts, PH_INIT);
   if ((result = applyopts(-1, optspr, PH_EARLY)) < 0)
      return result;
   if ((result = applyopts(-1, optspr, PH_PREOPEN)) < 0)
      return result;

   /* apply options to first FD */
   if ((result =
	applyopts(sock->dual.stream[0]->fd,
		  sock->dual.stream[0]->opts, PH_ALL))
       < 0) {
      return result;
   }
   if ((result = _xio_openlate(sock->dual.stream[0],
			       sock->dual.stream[0]->opts)) < 0) {
      return result;
   }
#if 0
   /* ignore this opt */
   retropt_bool(sock->dual.stream[0]->opts, OPT_COOL_WRITE);
#endif

   /* apply options to second FD */
   if ((result = applyopts(sock->dual.stream[1]->fd,
			   sock->dual.stream[1]->opts, PH_ALL)) < 0) {
      return result;
   }
   if ((result = _xio_openlate(sock->dual.stream[1],
			       sock->dual.stream[1]->opts)) < 0) {
      return result;
   }

#if 0
   if ((result = _xio_openlate(sock->dual.stream[1], optspr)) < 0) {
      return result;
   }
#endif

   Notice("reading from and writing to stdio");
   return 0;
}