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 tVFS_Node *retnode = (isServer ? &ret->ServerNode : &ret->ClientNode);
524 retnode->ReferenceCount ++;
531 tVFS_Node *PTY_MkNod(tVFS_Node *Node, const char *Name, Uint Mode)
533 // zero-length name means a numbered pty has been requested
534 if( Name[0] == '\0' || (Name[0] == '#' && Name[1] == '\0') )
536 tPTY *ret = PTY_Create(NULL, NULL, NULL, NULL, NULL);
539 return &ret->ServerNode;
542 // Otherwise return a named PTY
543 // TODO: Should the request be for '<name>s' or just '<name>'
545 tPTY *ret = PTY_Create(Name, NULL, NULL, NULL, NULL);
548 return &ret->ServerNode;
551 //\! Read from the client's input
552 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
554 tPTY *pty = Node->ImplPtr;
556 // Read from flushed queue
557 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
560 // If server has disconnected, return EIO
561 if( pty->ServerNode.ReferenceCount == 0 ) {
562 //Threads_PostSignal(SIGPIPE);
566 // Wait for data to be ready
567 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
569 errno = (timeout ? EWOULDBLOCK : EINTR);
573 Mutex_Acquire(&pty->InputMutex);
574 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
576 Mutex_Release(&pty->InputMutex);
578 if(pty->InputReadPos == pty->InputWritePos)
579 VFS_MarkAvaliable(Node, 0);
581 if(Length == 0 && !pty->HasHitEOF) {
589 //\! Write to the client's output
590 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
592 tPTY *pty = Node->ImplPtr;
594 // If the server has terminated, send SIGPIPE
595 if( pty->ServerNode.ReferenceCount == 0 )
597 //Threads_PostSignal(SIGPIPE);
602 // Write to either FIFO or directly to output function
605 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
609 // Write to output ringbuffer
610 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
611 &pty->OutputReadPos, &pty->OutputWritePos,
613 VFS_MarkAvaliable(&pty->ServerNode, 1);
619 int PTY_IOCtlClient(tVFS_Node *Node, int ID, void *Data)
621 tPTY *pty = Node->ImplPtr;
622 struct ptymode *mode = Data;
623 struct ptydims *dims = Data;
626 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
627 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
628 case DRV_IOCTL_VERSION: return 0x100;
629 case DRV_IOCTL_LOOKUP: return 0;
631 case PTY_IOCTL_GETMODE:
632 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
635 case PTY_IOCTL_SETMODE:
636 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
637 return PTY_SetAttrib(pty, NULL, mode, 1);
638 case PTY_IOCTL_GETDIMS:
639 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
642 case PTY_IOCTL_SETDIMS:
643 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
644 return PTY_SetAttrib(pty, dims, NULL, 1);
650 void PTY_ReferenceClient(tVFS_Node *Node)
652 Node->ReferenceCount ++;
653 // TODO: Add PID to list of client PIDs
654 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
657 void PTY_CloseClient(tVFS_Node *Node)
659 tPTY *pty = Node->ImplPtr;
660 Node->ReferenceCount --;
662 // Remove PID from list
663 // TODO: Maintain list of client processes
665 // Free structure if this was the last open handle
666 if( Node->ReferenceCount == 0 && pty->ServerNode.ReferenceCount == 0 )
668 // Free the structure! (Should be off the PTY list now)
673 //\! Read from the client's output
674 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
676 tPTY *pty = Node->ImplPtr;
678 // TODO: Prevent two servers fighting over client's output
681 // Kernel-land PTYs can't be read from userland
685 // Read back from fifo
686 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
687 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
689 errno = (timeout ? EWOULDBLOCK : EINTR);
693 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
694 &pty->OutputReadPos, &pty->OutputWritePos,
696 if( pty->OutputReadPos == pty->OutputWritePos )
697 VFS_MarkAvaliable(Node, 0);
698 VFS_MarkFull(&pty->ClientNode, 0);
703 //\! Write to the client's input
704 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
706 return PTY_SendInput(Node->ImplPtr, Buffer, Length);
709 int PTY_IOCtlServer(tVFS_Node *Node, int ID, void *Data)
711 tPTY *pty = Node->ImplPtr;
712 struct ptymode *mode = Data;
713 struct ptydims *dims = Data;
716 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
717 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
718 case DRV_IOCTL_VERSION: return 0x100;
719 case DRV_IOCTL_LOOKUP: return 0;
721 case PTY_IOCTL_GETMODE:
722 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
724 // ACK client's SETMODE
726 case PTY_IOCTL_SETMODE:
727 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
728 PTY_SetAttrib(pty, NULL, mode, 0);
730 case PTY_IOCTL_GETDIMS:
731 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
734 case PTY_IOCTL_SETDIMS:
735 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
736 PTY_SetAttrib(pty, dims, NULL, 0);
738 case PTY_IOCTL_GETID:
739 return pty->NumericName;
745 void PTY_CloseServer(tVFS_Node *Node)
747 tPTY *pty = Node->ImplPtr;
749 Node->ReferenceCount --;
750 // If reference count == 0, remove from main list
751 if( Node->ReferenceCount > 0 )
754 // Locate on list and remove
757 RWLock_AcquireWrite(&glPTY_NamedPTYs);
758 prev_np = &gpPTY_FirstNamedPTY;
761 RWLock_AcquireWrite(&glPTY_NumPTYs);
762 prev_np = &gpPTY_FirstNumPTY;
765 // Search list until *prev_np is equal to pty
766 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
770 if( *prev_np != pty ) {
771 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
774 *prev_np = pty->Next;
779 RWLock_Release(&glPTY_NamedPTYs);
783 RWLock_Release(&glPTY_NumPTYs);
787 // If there are no open children, we can safely free this PTY
788 if( pty->ClientNode.ReferenceCount == 0 )