Kernel/serial - Debugging added (disabled)
[tpg/acess2.git] / KernelLand / Kernel / drv / pty.c
index 1d1bdf3..d6713f9 100644 (file)
@@ -13,6 +13,7 @@
 #include <modules.h>
 #include <rwlock.h>
 #include <mutex.h>
+#include <posix_signals.h>
 
 // === CONSTANTS ===
 #define OUTPUT_RINGBUFFER_LEN  1024    // Number of bytes in output queue before client blocks
@@ -52,8 +53,8 @@ struct sPTY
        tVFS_Node       *ServerNode;
        tVFS_Node       ClientNode;
        tVFS_ACL        OwnerRW;
-       
-       // TODO: Maintain list of client PIDs
+
+       tPGID   ControllingProcGroup;
 };
 
 // === PROTOTYPES ===
@@ -120,12 +121,63 @@ int PTY_Install(char **Arguments)
 }
 
 // --- Management ---
-tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
+tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet, const struct ptydims *InitialDims, const struct ptymode *InitialMode)
 {
        tPTY    **prev_np = NULL;
        size_t  namelen;
         int    idx = 1;
-       if( Name && Name[0] )
+       
+       if( !Name )
+               Name = "";
+       
+       if( Name[0] == '\0' )
+       {
+               RWLock_AcquireWrite(&glPTY_NumPTYs);
+               // Get a pty ID if Name==NULL
+               prev_np = &gpPTY_FirstNumPTY;
+               for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
+               {
+                       if( pty->NumericName > idx )
+                               break;
+                       idx ++;
+               }
+               namelen = snprintf(NULL,0, "%u", idx);
+       }
+       else if( Name[strlen(Name)-1] == '#' )
+       {
+               // Sequenced PTYs
+               // - "gui#" would translate to "gui0", "gui1", "gui2", ...
+               //   whichever is free
+               prev_np = &gpPTY_FirstNamedPTY;
+
+               RWLock_AcquireWrite(&glPTY_NamedPTYs);
+               idx = 0;
+               namelen = strlen(Name)-1;
+               for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
+               {
+                        int    cmp = strncmp(pty->Name, Name, namelen);
+                       if( cmp < 0 )
+                               continue ;
+                       if( cmp > 0 )
+                               break;
+
+                       // Skip non-numbered
+                       if( pty->Name[namelen] == '\0' )
+                               continue ;                      
+
+                       // Find an unused index
+                       char    *name_end;
+                        int    this_idx = strtol(pty->Name+namelen, &name_end, 10);
+                       if( *name_end != '\0' )
+                               continue;
+                       if( this_idx > idx )
+                               break;
+                       idx ++;
+               }
+               
+               namelen += snprintf(NULL, 0, "%u", idx);
+       }
+       else
        {
                prev_np = &gpPTY_FirstNamedPTY;
                
@@ -135,7 +187,7 @@ tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_Req
                        errno = EINVAL;
                        return NULL;
                }
-               
+
                RWLock_AcquireWrite(&glPTY_NamedPTYs);
                // Detect duplicates
                for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
@@ -153,19 +205,6 @@ tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_Req
                namelen = strlen(Name);
                idx = -1;
        }
-       else
-       {
-               RWLock_AcquireWrite(&glPTY_NumPTYs);
-               // Get a pty ID if Name==NULL
-               prev_np = &gpPTY_FirstNumPTY;
-               for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
-               {
-                       if( pty->NumericName > idx )
-                               break;
-                       idx ++;
-               }
-               namelen = snprintf(NULL,0, "%u", idx);
-       }
        
        tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
        if(!ret) {
@@ -178,8 +217,10 @@ tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_Req
        *prev_np = ret;
        // - PTY Name (Used by VT)
        ret->Name = (char*)(ret + 1);
-       if(Name)
+       if( idx == -1 )
                strcpy(ret->Name, Name);
+       else if( Name[0] )
+               sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
        else
                sprintf(ret->Name, "%u", idx);
        ret->NumericName = idx;
@@ -188,6 +229,11 @@ tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_Req
        ret->OutputFcn = Output;
        ret->ReqResize = ReqResize;
        ret->ModeSet = ModeSet;
+       // - Initialise modes
+       if( InitialDims )
+               ret->Dims = *InitialDims;
+       if( InitialMode )
+               ret->Mode = *InitialMode;
        // - Client node
        ret->ClientNode.ImplPtr = ret;
        ret->ClientNode.Type = &gPTY_NodeType_Client;
@@ -199,7 +245,7 @@ tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_Req
        ret->OwnerRW.Ent.ID = Threads_GetUID();
        ret->OwnerRW.Perm.Perms = -1;
 
-       if( Name && Name[0] ) {
+       if( Name[0] ) {
                giPTY_NamedCount ++;
                RWLock_Release(&glPTY_NamedPTYs);
        }
@@ -216,6 +262,7 @@ int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *M
        if( Mode )
        {
                // (for now) userland terminals can't be put into framebuffer mode
+               // - Userland PTYs are streams, framebuffer is a block
                if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
                        errno = EINVAL;
                        return -1;
@@ -229,14 +276,15 @@ int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *M
                        }
                        else if( !PTY->OutputFcn )
                        {
-                               Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
-                               // Block write until acked
-                               // ACK by server doing GETMODE
+                               Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
+                               // Block slave write until master ACKs
+                               // 0-length read on master indicates need to GETMODE
                        }
                }
                else
                {
                        // Should the client be informed that the server just twiddled the modes?
+                       Log_Warning("PTY", "Server changed mode, TODO: inform client?");
                }
                LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
                PTY->Mode = *Mode;
@@ -254,11 +302,14 @@ int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *M
                        else if( !PTY->OutputFcn )
                        {
                                // Inform server process... somehow
+                               Log_Warning("PTY", "TODO: Inform server of client resize request");
                        }
                }
                else
                {
                        // SIGWINSZ to client
+                       if( PTY->ControllingProcGroup > 0 )
+                               Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
                }
                LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
                PTY->Dims = *Dims;
@@ -274,9 +325,7 @@ void PTY_Close(tPTY *PTY)
 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
 {
        size_t space = (*rd - *wr + buflen - 1) % buflen;
-       ENTER("pbuf ibuflen prd pwr pdata ilen", buf, buflen, rd, wr, data, len);
        len = MIN(space, len);
-       LOG("space = %i, *rd = %i, *wr = %i", space, *rd, *wr);
        if(*wr + len >= buflen) {
                size_t prelen = buflen - *wr;
                memcpy((char*)buf + *wr, data, prelen);
@@ -287,7 +336,6 @@ size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, s
                memcpy((char*)buf + *wr, data, len);
                *wr += len;
        }
-       LEAVE('i', len);
        return len;
 }
 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
@@ -319,7 +367,7 @@ size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
        Mutex_Release(&PTY->InputMutex);
 
        VFS_MarkAvaliable(&PTY->ClientNode, 1);
-       if(ret < Length)
+       if(ret < Length && PTY->ServerNode)
                VFS_MarkFull(PTY->ServerNode, 1);       
 
        return ret;
@@ -330,21 +378,22 @@ size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
        size_t  ret = 1, print = 1;
        
        // Input mode stuff only counts for text output mode
-       // - Any other is Uint32 keypresses
+       // - Any other mode sends Uint32 keypresses
        if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
                return PTY_int_WriteInput(PTY, Input, Length);
-       // If in raw mode, flush directlr
+       // If in raw mode, flush directly
        if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
                return PTY_int_WriteInput(PTY, Input, Length);
        
        if( PTY->Mode.InputMode & PTYIMODE_CANON )
        {
-               const char      char_bs = '\b';
+               
                switch(Input[0])
                {
                case 3: // INTR - ^C
-                       // TODO: Send SIGINT
-                       // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
+                       // Send SIGINT
+                       if( PTY->ControllingProcGroup > 0 )
+                               Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
                        print = 0;
                        break;
                case 4: // EOF - ^D
@@ -354,17 +403,21 @@ size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
                        print = 0;
                        break;
                case 8: // Backspace
-                       if(PTY->LineLength != 0)
+                       if(PTY->LineLength != 0) {
                                PTY->LineLength --;
+                               PTY_WriteClient(&PTY->ClientNode, 0, 3, "\b \b", 0);
+                       }
+                       print = 0;
                        break;
                case 'w'-'a':   // Word erase
                        while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
-                               PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
+                               PTY_WriteClient(&PTY->ClientNode, 0, 1, "\b", 0);
+                       PTY_WriteClient(&PTY->ClientNode, 0, 3, "\x1b[K", 0);
                        print = 0;
                        break;
                case 'u'-'a':   // Kill
-                       while(PTY->LineLength > 0)
-                               PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
+                       PTY_WriteClient(&PTY->ClientNode, 0, 8, "\x1b[2K\x1b[0G", 0);
+                       PTY->LineLength = 0;
                        print = 0;
                        break;
                case 'v'-'a':
@@ -397,7 +450,24 @@ size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
        }
        else
        {
-               ret = PTY_int_WriteInput(PTY, Input, Length);
+               #if 0
+               if( PTY->Mode.InputMode & PTYIMODE_NLCR )
+               {
+                       if( Input[0] == '\n' ) {
+                               char ch = '\r';
+                               ret = PTY_int_WriteInput(PTY, &ch, 1);
+                       }
+                       else {
+                                int    i;
+                               for( i = 0; i < Length && Input[i] != '\n'; i ++ )
+                                       ;
+                               ret = PTY_int_WriteInput(PTY, Input, i);
+                       }
+               }
+               // TODO: CRNL mode?
+               else
+               #endif
+                       ret = PTY_int_WriteInput(PTY, Input, Length);
        }
        
        // Echo if requested
@@ -442,12 +512,10 @@ int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
        }
 
        if( !pty ) {
-               LOG("%i out of range", Pos);
                return -1;
        }
 
-       strncpy(Name, pty->Name, FILENAME_MAX)  
-       LOG("Return '%s'", Name);
+       strncpy(Name, pty->Name, FILENAME_MAX);
        return 0;
 }
 
@@ -498,6 +566,7 @@ tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
                }
                RWLock_Release(&glPTY_NamedPTYs);
        }
+//     Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
        if( ret ) {
                tVFS_Node       *retnode = &ret->ClientNode;
                retnode->ReferenceCount ++;
@@ -555,7 +624,7 @@ size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void
        // If the server has terminated, send SIGPIPE
        if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
        {
-               //Threads_PostSignal(SIGPIPE);
+               Threads_PostSignal(SIGPIPE);
                errno = EIO;
                return -1;
        }       
@@ -567,31 +636,37 @@ size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void
        }
        
        // FIFO
-       tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
-        int    rv;
-       
-       rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
-       if(!rv ) {
-               errno = (timeout ? EWOULDBLOCK : EINTR);
-               return -1;
-       }
-       
-       // Write to output ringbuffer
-       Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
-               &pty->OutputReadPos, &pty->OutputWritePos,
-               Buffer, Length);
-       VFS_MarkAvaliable(pty->ServerNode, 1);
-       if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
-               VFS_MarkFull(Node, 1);
+       size_t remaining = Length;
+       do
+       {
+               tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
+                int    rv;
+               
+               rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
+               if(!rv) {
+                       errno = (timeout ? EWOULDBLOCK : EINTR);
+                       return -1;
+               }
+               
+               // Write to output ringbuffer
+               size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
+                       &pty->OutputReadPos, &pty->OutputWritePos,
+                       Buffer, remaining);
+               LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
+               VFS_MarkAvaliable(pty->ServerNode, 1);
+               if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
+                       VFS_MarkFull(Node, 1);
+               
+               remaining -= written;
+               Buffer = (const char*)Buffer + written;
+       } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
        
-       return Length;
+       return Length - remaining;
 }
 
 void PTY_ReferenceClient(tVFS_Node *Node)
 {
        Node->ReferenceCount ++;
-       // TODO: Add PID to list of client PIDs
-//     Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
 }
 
 void PTY_CloseClient(tVFS_Node *Node)
@@ -640,6 +715,7 @@ size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer
        Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
                &pty->OutputReadPos, &pty->OutputWritePos,
                Buffer, Length);
+       LOG("Read %i '%.*s'", Length, Length, Buffer);
        if( pty->OutputReadPos == pty->OutputWritePos )
                VFS_MarkAvaliable(Node, 0);
        VFS_MarkFull(&pty->ClientNode, 0);
@@ -683,7 +759,7 @@ void PTY_CloseServer(tVFS_Node *Node)
        
        // Locate on list and remove
        tPTY    **prev_np;
-       if( pty->NumericName == 0 ) {
+       if( pty->NumericName == -1 ) {
                RWLock_AcquireWrite(&glPTY_NamedPTYs);
                prev_np = &gpPTY_FirstNamedPTY;
        }
@@ -705,7 +781,7 @@ void PTY_CloseServer(tVFS_Node *Node)
        }
        
        // Clean up lock
-       if( pty->NumericName == 0 ) {
+       if( pty->NumericName == -1 ) {
                RWLock_Release(&glPTY_NamedPTYs);
                giPTY_NamedCount --;
        }
@@ -714,6 +790,11 @@ void PTY_CloseServer(tVFS_Node *Node)
                giPTY_NumCount --;
        }
 
+       // Send SIGHUP to controling PGID
+       if( pty->ControllingProcGroup > 0 ) {
+               Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
+       }
+
        // If there are no open children, we can safely free this PTY
        if( pty->ClientNode.ReferenceCount == 0 ) {
                free(Node);
@@ -729,6 +810,8 @@ int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
        
        int     is_server = !pty || Node == pty->ServerNode;
 
+       LOG("(%i,%p) %s", ID, Data, (is_server?"Server":"Client"));
+
        switch(ID)
        {
        case DRV_IOCTL_TYPE:    return DRV_TYPE_TERMINAL;
@@ -772,12 +855,21 @@ int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
        case PTY_IOCTL_SETID:
                if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
                if( pty )       return EALREADY;
-               pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
+               pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
                if(pty == NULL)
                        return 1;
                Node->ImplPtr = pty;
                pty->ServerNode = Node;
                return 0;
+       case PTY_IOCTL_SETPGRP:
+               // TODO: Should this only be done by client?
+               if( Data )
+               {
+                       if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
+                       pty->ControllingProcGroup = *(tPGID*)Data;
+                       Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
+               }
+               return pty->ControllingProcGroup;
        }
        errno = ENOSYS;
        return -1;

UCC git Repository :: git.ucc.asn.au