3 * - By John Hodge (thePowersGang)
18 #define OUTPUT_RINGBUFFER_LEN 1024 // Number of bytes in output queue before client blocks
19 #define INPUT_RINGBUFFER_LEN 256 // Number of bytes in input queue before being dropped
20 #define INPUT_LINE_LEN 256
31 tPTY_OutputFcn OutputFcn;
32 tPTY_ReqResize ReqResize;
42 char InputData[INPUT_RINGBUFFER_LEN];
45 char LineData[INPUT_LINE_LEN];
50 char OutputData[OUTPUT_RINGBUFFER_LEN];
56 // TODO: Maintain list of client PIDs
60 int PTY_Install(char **Arguments);
61 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
62 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
63 tVFS_Node *PTY_MkNod(tVFS_Node *Node, const char *Name, Uint Mode);
65 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
66 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
67 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
68 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
70 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
71 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
72 int PTY_IOCtlClient(tVFS_Node *Node, int ID, void *Arg);
73 void PTY_ReferenceClient(tVFS_Node *Node);
74 void PTY_CloseClient(tVFS_Node *Node);
75 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
76 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
77 int PTY_IOCtlServer(tVFS_Node *Node, int ID, void *Arg);
78 void PTY_CloseServer(tVFS_Node *Node);
81 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
82 tVFS_NodeType gPTY_NodeType_Root = {
83 .TypeName = "PTY-Root",
84 .ReadDir = PTY_ReadDir,
85 .FindDir = PTY_FindDir,
88 tVFS_NodeType gPTY_NodeType_Client = {
89 .TypeName = "PTY-Client",
90 .Read = PTY_ReadClient,
91 .Write = PTY_WriteClient,
92 .IOCtl = PTY_IOCtlClient,
93 .Reference = PTY_ReferenceClient,
94 .Close = PTY_CloseClient
96 tVFS_NodeType gPTY_NodeType_Server = {
97 .TypeName = "PTY-Server",
98 .Read = PTY_ReadServer,
99 .Write = PTY_WriteServer,
100 .IOCtl = PTY_IOCtlServer,
101 .Close = PTY_CloseServer
103 tDevFS_Driver gPTY_Driver = {
106 .Flags = VFS_FFLAG_DIRECTORY,
107 .Type = &gPTY_NodeType_Root,
112 tRWLock glPTY_NumPTYs;
113 tPTY *gpPTY_FirstNumPTY;
114 int giPTY_NamedCount;
115 tRWLock glPTY_NamedPTYs;
116 tPTY *gpPTY_FirstNamedPTY;
119 int PTY_Install(char **Arguments)
121 DevFS_AddDevice(&gPTY_Driver);
122 return MODULE_ERR_OK;
125 // --- Management ---
126 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
128 tPTY **prev_np = NULL;
131 if( Name && Name[0] )
133 prev_np = &gpPTY_FirstNamedPTY;
135 // Check the name isn't decimal
137 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
142 RWLock_AcquireWrite(&glPTY_NamedPTYs);
144 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
146 int cmp = strcmp(pty->Name, Name);
150 RWLock_Release(&glPTY_NamedPTYs);
156 namelen = strlen(Name);
161 RWLock_AcquireWrite(&glPTY_NumPTYs);
162 // Get a pty ID if Name==NULL
163 prev_np = &gpPTY_FirstNumPTY;
164 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
166 if( pty->NumericName > idx )
173 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
179 // - List maintainance
180 ret->Next = *prev_np;
182 // - PTY Name (Used by VT)
183 ret->Name = (char*)(ret + 1);
185 strcpy(ret->Name, Name);
188 ret->NumericName = idx;
189 // - Output function and handle (same again)
190 ret->OutputHandle = Handle;
191 ret->OutputFcn = Output;
192 ret->ReqResize = ReqResize;
193 ret->ModeSet = ModeSet;
195 ret->ServerNode.ImplPtr = ret;
196 ret->ServerNode.Type = &gPTY_NodeType_Server;
197 ret->ServerNode.UID = Threads_GetUID();
198 ret->ServerNode.GID = Threads_GetGID();
199 ret->ServerNode.NumACLs = 1;
200 ret->ServerNode.ACLs = &ret->OwnerRW;
201 ret->ServerNode.ReferenceCount = (Output ? 1 : 0); // Prevent a userland close killing a kernel pty
203 ret->ClientNode.ImplPtr = ret;
204 ret->ClientNode.Type = &gPTY_NodeType_Client;
205 ret->ClientNode.UID = Threads_GetUID();
206 ret->ClientNode.GID = Threads_GetGID();
207 ret->ClientNode.NumACLs = 1;
208 ret->ClientNode.ACLs = &ret->OwnerRW;
209 // - Owner Read-Write ACL
210 ret->OwnerRW.Ent.ID = Threads_GetUID();
211 ret->OwnerRW.Perm.Perms = -1;
213 if( Name && Name[0] ) {
215 RWLock_Release(&glPTY_NamedPTYs);
219 RWLock_Release(&glPTY_NumPTYs);
225 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
229 // (for now) userland terminals can't be put into framebuffer mode
230 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
236 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
241 else if( !PTY->OutputFcn )
243 Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
244 // Block write until acked
245 // ACK by server doing GETMODE
250 // Should the client be informed that the server just twiddled the modes?
252 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
260 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
265 else if( !PTY->OutputFcn )
267 // Inform server process... somehow
272 // SIGWINSZ to client
274 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
280 void PTY_Close(tPTY *PTY)
285 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
287 size_t space = (*rd - *wr + buflen - 1) % buflen;
288 ENTER("pbuf ibuflen prd pwr pdata ilen", buf, buflen, rd, wr, data, len);
289 len = MIN(space, len);
290 LOG("space = %i, *rd = %i, *wr = %i", space, *rd, *wr);
291 if(*wr + len >= buflen) {
292 size_t prelen = buflen - *wr;
293 memcpy((char*)buf + *wr, data, prelen);
294 memcpy(buf, (char*)data + prelen, len - prelen);
298 memcpy((char*)buf + *wr, data, len);
304 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
306 size_t space = (*wr - *rd + buflen) % buflen;
307 len = MIN(space, len);
308 if(*rd + len >= buflen) {
309 size_t prelen = buflen - *rd;
310 memcpy(data, (char*)buf + *rd, prelen);
311 memcpy((char*)data + prelen, buf, len - prelen);
315 memcpy(data, (char*)buf + *rd, len);
321 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
325 Mutex_Acquire(&PTY->InputMutex);
327 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
330 Mutex_Release(&PTY->InputMutex);
332 VFS_MarkAvaliable(&PTY->ClientNode, 1);
334 VFS_MarkFull(&PTY->ServerNode, 1);
339 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
341 size_t ret = 1, print = 1;
343 // Input mode stuff only counts for text output mode
344 // - Any other is Uint32 keypresses
345 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
346 return PTY_int_WriteInput(PTY, Input, Length);
347 // If in raw mode, flush directlr
348 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
349 return PTY_int_WriteInput(PTY, Input, Length);
351 if( PTY->Mode.InputMode & PTYIMODE_CANON )
353 const char char_bs = '\b';
358 // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
362 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
363 PTY->HasHitEOF = (PTY->LineLength == 0);
368 if(PTY->LineLength != 0)
371 case 'w'-'a': // Word erase
372 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
373 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
376 case 'u'-'a': // Kill
377 while(PTY->LineLength > 0)
378 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
388 if(PTY->LineLength == INPUT_LINE_LEN) {
389 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
392 PTY->LineData[PTY->LineLength++] = '\n';
393 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
396 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
401 if(PTY->LineLength == INPUT_LINE_LEN) {
402 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
405 PTY->LineData[PTY->LineLength++] = Input[0];
411 ret = PTY_int_WriteInput(PTY, Input, Length);
415 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
417 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
423 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
426 while( ret < Length && !PTY->ClientNode.BufferFull )
428 // TODO: Detect blocking?
429 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
435 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
439 if( idx < giPTY_NumCount * 2 )
441 RWLock_AcquireRead(&glPTY_NumPTYs);
442 for( pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
448 RWLock_Release(&glPTY_NumPTYs);
450 else if( idx < (giPTY_NumCount + giPTY_NamedCount) * 2 )
452 idx -= giPTY_NumCount*2;
453 RWLock_AcquireRead(&glPTY_NamedPTYs);
454 for( pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
460 RWLock_Release(&glPTY_NamedPTYs);
465 LOG("%i out of range", Pos);
470 snprintf(Name, FILENAME_MAX, "%s%c", pty->Name, (idx == 0 ? 'c' : 's'));
472 snprintf(Name, FILENAME_MAX, "%i%c", pty->NumericName, (idx == 0 ? 'c' : 's'));
473 LOG("Return '%s'", Name);
477 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
480 int num = strtol(Name, &end, 10);
482 if( Name[0] == '\0' || Name[1] == '\0' )
485 size_t len = strlen(Name);
486 if( Name[len-1] != 'c' && Name[len-1] != 's' )
488 int isServer = (Name[len-1] != 'c');
491 if( num && (end[0] == 'c' || end[0] == 's') && end[1] == '\0' )
494 RWLock_AcquireRead(&glPTY_NumPTYs);
495 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
497 if( pty->NumericName > num )
499 if( pty->NumericName == num ) {
504 RWLock_Release(&glPTY_NumPTYs);
509 RWLock_AcquireRead(&glPTY_NamedPTYs);
510 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
512 int cmp = strncmp(pty->Name, Name, len-1);
515 if(cmp == 0 && pty->Name[len-1] == '\0' ) {
520 RWLock_Release(&glPTY_NamedPTYs);
523 return (isServer ? &ret->ServerNode : &ret->ClientNode);
528 tVFS_Node *PTY_MkNod(tVFS_Node *Node, const char *Name, Uint Mode)
530 // zero-length name means a numbered pty has been requested
531 if( Name[0] == '\0' || (Name[0] == '#' && Name[1] == '\0') )
533 tPTY *ret = PTY_Create(NULL, NULL, NULL, NULL, NULL);
536 return &ret->ServerNode;
539 // Otherwise return a named PTY
540 // TODO: Should the request be for '<name>s' or just '<name>'
542 tPTY *ret = PTY_Create(Name, NULL, NULL, NULL, NULL);
545 return &ret->ServerNode;
548 //\! Read from the client's input
549 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
551 tPTY *pty = Node->ImplPtr;
553 // Read from flushed queue
554 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
557 // If server has disconnected, return EIO
558 if( pty->ServerNode.ReferenceCount == 0 ) {
559 //Threads_PostSignal(SIGPIPE);
563 // Wait for data to be ready
564 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
566 errno = (timeout ? EWOULDBLOCK : EINTR);
570 Mutex_Acquire(&pty->InputMutex);
571 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
573 Mutex_Release(&pty->InputMutex);
575 if(pty->InputReadPos == pty->InputWritePos)
576 VFS_MarkAvaliable(Node, 0);
578 if(Length == 0 && !pty->HasHitEOF) {
586 //\! Write to the client's output
587 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
589 tPTY *pty = Node->ImplPtr;
591 // If the server has terminated, send SIGPIPE
592 if( pty->ServerNode.ReferenceCount == 0 )
594 //Threads_PostSignal(SIGPIPE);
599 // Write to either FIFO or directly to output function
602 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
606 // Write to output ringbuffer
607 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
608 &pty->OutputReadPos, &pty->OutputWritePos,
610 VFS_MarkAvaliable(&pty->ServerNode, 1);
616 int PTY_IOCtlClient(tVFS_Node *Node, int ID, void *Data)
618 tPTY *pty = Node->ImplPtr;
619 struct ptymode *mode = Data;
620 struct ptydims *dims = Data;
623 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
624 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
625 case DRV_IOCTL_VERSION: return 0x100;
626 case DRV_IOCTL_LOOKUP: return 0;
628 case PTY_IOCTL_GETMODE:
629 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
632 case PTY_IOCTL_SETMODE:
633 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
634 return PTY_SetAttrib(pty, NULL, mode, 1);
635 case PTY_IOCTL_GETDIMS:
636 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
639 case PTY_IOCTL_SETDIMS:
640 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
641 return PTY_SetAttrib(pty, dims, NULL, 1);
647 void PTY_ReferenceClient(tVFS_Node *Node)
649 Node->ReferenceCount ++;
650 // TODO: Add PID to list of client PIDs
651 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
654 void PTY_CloseClient(tVFS_Node *Node)
656 tPTY *pty = Node->ImplPtr;
657 Node->ReferenceCount --;
659 // Remove PID from list
660 // TODO: Maintain list of client processes
662 // Free structure if this was the last open handle
663 if( Node->ReferenceCount == 0 && pty->ServerNode.ReferenceCount == 0 )
665 // Free the structure! (Should be off the PTY list now)
670 //\! Read from the client's output
671 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
673 tPTY *pty = Node->ImplPtr;
675 // TODO: Prevent two servers fighting over client's output
678 // Kernel-land PTYs can't be read from userland
682 // Read back from fifo
683 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
684 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
686 errno = (timeout ? EWOULDBLOCK : EINTR);
690 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
691 &pty->OutputReadPos, &pty->OutputWritePos,
693 if( pty->OutputReadPos == pty->OutputWritePos )
694 VFS_MarkAvaliable(Node, 0);
695 VFS_MarkFull(&pty->ClientNode, 0);
700 //\! Write to the client's input
701 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
703 return PTY_SendInput(Node->ImplPtr, Buffer, Length);
706 int PTY_IOCtlServer(tVFS_Node *Node, int ID, void *Data)
708 tPTY *pty = Node->ImplPtr;
709 struct ptymode *mode = Data;
710 struct ptydims *dims = Data;
713 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
714 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
715 case DRV_IOCTL_VERSION: return 0x100;
716 case DRV_IOCTL_LOOKUP: return 0;
718 case PTY_IOCTL_GETMODE:
719 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
721 // ACK client's SETMODE
723 case PTY_IOCTL_SETMODE:
724 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
725 PTY_SetAttrib(pty, NULL, mode, 0);
727 case PTY_IOCTL_GETDIMS:
728 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
731 case PTY_IOCTL_SETDIMS:
732 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
733 PTY_SetAttrib(pty, dims, NULL, 0);
735 case PTY_IOCTL_GETID:
736 return pty->NumericName;
742 void PTY_CloseServer(tVFS_Node *Node)
744 tPTY *pty = Node->ImplPtr;
746 Node->ReferenceCount --;
747 // If reference count == 0, remove from main list
748 if( Node->ReferenceCount > 0 )
751 // Locate on list and remove
754 RWLock_AcquireWrite(&glPTY_NamedPTYs);
755 prev_np = &gpPTY_FirstNamedPTY;
758 RWLock_AcquireWrite(&glPTY_NumPTYs);
759 prev_np = &gpPTY_FirstNumPTY;
762 // Search list until *prev_np is equal to pty
763 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
767 if( *prev_np != pty ) {
768 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
771 *prev_np = pty->Next;
776 RWLock_Release(&glPTY_NamedPTYs);
780 RWLock_Release(&glPTY_NumPTYs);
784 // If there are no open children, we can safely free this PTY
785 if( pty->ClientNode.ReferenceCount == 0 )