3 * - By John Hodge (thePowersGang)
16 #include <posix_signals.h>
19 #define OUTPUT_RINGBUFFER_LEN 1024 // Number of bytes in output queue before client blocks
20 #define INPUT_RINGBUFFER_LEN 256 // Number of bytes in input queue before being dropped
21 #define INPUT_LINE_LEN 256
32 tPTY_OutputFcn OutputFcn;
33 tPTY_ReqResize ReqResize;
43 char InputData[INPUT_RINGBUFFER_LEN];
46 char LineData[INPUT_LINE_LEN];
51 char OutputData[OUTPUT_RINGBUFFER_LEN];
53 tVFS_Node *ServerNode;
57 tPGID ControllingProcGroup;
61 int PTY_Install(char **Arguments);
62 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
63 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
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 void PTY_ReferenceClient(tVFS_Node *Node);
73 void PTY_CloseClient(tVFS_Node *Node);
74 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
75 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
76 void PTY_CloseServer(tVFS_Node *Node);
77 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
80 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
81 tVFS_NodeType gPTY_NodeType_Root = {
82 .TypeName = "PTY-Root",
83 .ReadDir = PTY_ReadDir,
84 .FindDir = PTY_FindDir,
86 tVFS_NodeType gPTY_NodeType_Client = {
87 .TypeName = "PTY-Client",
88 .Read = PTY_ReadClient,
89 .Write = PTY_WriteClient,
91 .Reference = PTY_ReferenceClient,
92 .Close = PTY_CloseClient
94 tVFS_NodeType gPTY_NodeType_Server = {
95 .TypeName = "PTY-Server",
96 .Read = PTY_ReadServer,
97 .Write = PTY_WriteServer,
99 .Close = PTY_CloseServer
101 tDevFS_Driver gPTY_Driver = {
104 .Flags = VFS_FFLAG_DIRECTORY,
105 .Type = &gPTY_NodeType_Root,
110 tRWLock glPTY_NumPTYs;
111 tPTY *gpPTY_FirstNumPTY;
112 int giPTY_NamedCount;
113 tRWLock glPTY_NamedPTYs;
114 tPTY *gpPTY_FirstNamedPTY;
117 int PTY_Install(char **Arguments)
119 DevFS_AddDevice(&gPTY_Driver);
120 return MODULE_ERR_OK;
123 // --- Management ---
124 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
126 tPTY **prev_np = NULL;
129 if( !Name || Name[0] == '\0' )
131 RWLock_AcquireWrite(&glPTY_NumPTYs);
132 // Get a pty ID if Name==NULL
133 prev_np = &gpPTY_FirstNumPTY;
134 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
136 if( pty->NumericName > idx )
140 namelen = snprintf(NULL,0, "%u", idx);
142 else if( Name[strlen(Name)-1] == '#' )
145 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
147 prev_np = &gpPTY_FirstNamedPTY;
150 namelen = strlen(Name)-1;
151 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
153 int cmp = strncmp(pty->Name, Name, namelen);
160 if( pty->Name[namelen] == '\0' )
163 // Find an unused index
165 int this_idx = strtol(pty->Name+namelen, &name_end, 10);
166 if( *name_end != '\0' )
173 namelen += snprintf(NULL, 0, "%u", idx);
177 prev_np = &gpPTY_FirstNamedPTY;
179 // Check the name isn't decimal
181 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
186 RWLock_AcquireWrite(&glPTY_NamedPTYs);
188 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
190 int cmp = strcmp(pty->Name, Name);
194 RWLock_Release(&glPTY_NamedPTYs);
200 namelen = strlen(Name);
204 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
210 // - List maintainance
211 ret->Next = *prev_np;
213 // - PTY Name (Used by VT)
214 ret->Name = (char*)(ret + 1);
216 strcpy(ret->Name, Name);
219 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
221 ret->NumericName = idx;
222 // - Output function and handle (same again)
223 ret->OutputHandle = Handle;
224 ret->OutputFcn = Output;
225 ret->ReqResize = ReqResize;
226 ret->ModeSet = ModeSet;
228 ret->ClientNode.ImplPtr = ret;
229 ret->ClientNode.Type = &gPTY_NodeType_Client;
230 ret->ClientNode.UID = Threads_GetUID();
231 ret->ClientNode.GID = Threads_GetGID();
232 ret->ClientNode.NumACLs = 1;
233 ret->ClientNode.ACLs = &ret->OwnerRW;
234 // - Owner Read-Write ACL
235 ret->OwnerRW.Ent.ID = Threads_GetUID();
236 ret->OwnerRW.Perm.Perms = -1;
238 if( Name && Name[0] ) {
240 RWLock_Release(&glPTY_NamedPTYs);
244 RWLock_Release(&glPTY_NumPTYs);
250 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
254 // (for now) userland terminals can't be put into framebuffer mode
255 // - Userland PTYs are streams, framebuffer is a block
256 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
262 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
267 else if( !PTY->OutputFcn )
269 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
270 // Block slave write until master ACKs
271 // 0-length read on master indicates need to GETMODE
276 // Should the client be informed that the server just twiddled the modes?
277 Log_Warning("PTY", "Server changed mode, TODO: inform client?");
279 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
287 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
292 else if( !PTY->OutputFcn )
294 // Inform server process... somehow
295 Log_Warning("PTY", "TODO: Inform server of client resize request");
300 // SIGWINSZ to client
301 Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
303 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
309 void PTY_Close(tPTY *PTY)
314 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
316 size_t space = (*rd - *wr + buflen - 1) % buflen;
317 len = MIN(space, len);
318 if(*wr + len >= buflen) {
319 size_t prelen = buflen - *wr;
320 memcpy((char*)buf + *wr, data, prelen);
321 memcpy(buf, (char*)data + prelen, len - prelen);
325 memcpy((char*)buf + *wr, data, len);
330 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
332 size_t space = (*wr - *rd + buflen) % buflen;
333 len = MIN(space, len);
334 if(*rd + len >= buflen) {
335 size_t prelen = buflen - *rd;
336 memcpy(data, (char*)buf + *rd, prelen);
337 memcpy((char*)data + prelen, buf, len - prelen);
341 memcpy(data, (char*)buf + *rd, len);
347 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
351 Mutex_Acquire(&PTY->InputMutex);
353 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
356 Mutex_Release(&PTY->InputMutex);
358 VFS_MarkAvaliable(&PTY->ClientNode, 1);
359 if(ret < Length && PTY->ServerNode)
360 VFS_MarkFull(PTY->ServerNode, 1);
365 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
367 size_t ret = 1, print = 1;
369 // Input mode stuff only counts for text output mode
370 // - Any other is Uint32 keypresses
371 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
372 return PTY_int_WriteInput(PTY, Input, Length);
373 // If in raw mode, flush directlr
374 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
375 return PTY_int_WriteInput(PTY, Input, Length);
377 if( PTY->Mode.InputMode & PTYIMODE_CANON )
379 const char char_bs = '\b';
384 Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
388 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
389 PTY->HasHitEOF = (PTY->LineLength == 0);
394 if(PTY->LineLength != 0)
397 case 'w'-'a': // Word erase
398 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
399 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
402 case 'u'-'a': // Kill
403 while(PTY->LineLength > 0)
404 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
414 if(PTY->LineLength == INPUT_LINE_LEN) {
415 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
418 PTY->LineData[PTY->LineLength++] = '\n';
419 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
422 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
427 if(PTY->LineLength == INPUT_LINE_LEN) {
428 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
431 PTY->LineData[PTY->LineLength++] = Input[0];
437 ret = PTY_int_WriteInput(PTY, Input, Length);
441 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
443 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
449 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
452 while( ret < Length && !PTY->ClientNode.BufferFull )
454 // TODO: Detect blocking?
455 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
461 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
465 if( idx < giPTY_NumCount )
467 RWLock_AcquireRead(&glPTY_NumPTYs);
468 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
470 RWLock_Release(&glPTY_NumPTYs);
472 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
474 idx -= giPTY_NumCount;
475 RWLock_AcquireRead(&glPTY_NamedPTYs);
476 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
478 RWLock_Release(&glPTY_NamedPTYs);
485 strncpy(Name, pty->Name, FILENAME_MAX);
489 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
492 int num = strtol(Name, &end, 10);
494 if( strcmp(Name, "ptmx") == 0 ) {
495 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
497 ret->Type = &gPTY_NodeType_Server;
501 if( Name[0] == '\0' )
505 if( num && end[0] == '\0' )
508 RWLock_AcquireRead(&glPTY_NumPTYs);
509 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
511 if( pty->NumericName > num )
513 if( pty->NumericName == num ) {
518 RWLock_Release(&glPTY_NumPTYs);
523 RWLock_AcquireRead(&glPTY_NamedPTYs);
524 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
526 int cmp = strcmp(pty->Name, Name);
534 RWLock_Release(&glPTY_NamedPTYs);
536 // Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
538 tVFS_Node *retnode = &ret->ClientNode;
539 retnode->ReferenceCount ++;
546 //\! Read from the client's input
547 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
549 tPTY *pty = Node->ImplPtr;
551 // Read from flushed queue
552 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
555 // If server has disconnected, return EIO
556 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
557 //Threads_PostSignal(SIGPIPE);
561 // Wait for data to be ready
562 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
564 errno = (timeout ? EWOULDBLOCK : EINTR);
568 Mutex_Acquire(&pty->InputMutex);
569 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
571 if( Length && pty->ServerNode )
572 VFS_MarkFull(pty->ServerNode, 0);
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 && pty->ServerNode->ReferenceCount == 0 )
594 Threads_PostSignal(SIGPIPE);
599 // Write to either FIFO or directly to output function
600 if( pty->OutputFcn ) {
601 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
606 size_t remaining = Length;
609 tTime timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
612 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
614 errno = (timeout ? EWOULDBLOCK : EINTR);
618 // Write to output ringbuffer
619 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
620 &pty->OutputReadPos, &pty->OutputWritePos,
622 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
623 VFS_MarkAvaliable(pty->ServerNode, 1);
624 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
625 VFS_MarkFull(Node, 1);
627 remaining -= written;
628 Buffer = (const char*)Buffer + written;
629 } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
631 return Length - remaining;
634 void PTY_ReferenceClient(tVFS_Node *Node)
636 Node->ReferenceCount ++;
639 void PTY_CloseClient(tVFS_Node *Node)
641 tPTY *pty = Node->ImplPtr;
642 Node->ReferenceCount --;
644 // Remove PID from list
645 // TODO: Maintain list of client processes
647 // Free structure if this was the last open handle
648 if( Node->ReferenceCount > 0 )
650 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
652 // Free the structure! (Should be off the PTY list now)
653 free(pty->ServerNode);
658 //\! Read from the client's output
659 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
661 tPTY *pty = Node->ImplPtr;
667 // TODO: Prevent two servers fighting over client's output
670 // Kernel-land PTYs can't be read from userland
674 // Read back from fifo
675 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
676 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
678 errno = (timeout ? EWOULDBLOCK : EINTR);
682 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
683 &pty->OutputReadPos, &pty->OutputWritePos,
685 LOG("Read %i '%.*s'", Length, Length, Buffer);
686 if( pty->OutputReadPos == pty->OutputWritePos )
687 VFS_MarkAvaliable(Node, 0);
688 VFS_MarkFull(&pty->ClientNode, 0);
693 //\! Write to the client's input
694 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
696 tPTY *pty = Node->ImplPtr;
702 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
703 int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
705 errno = (timeout ? EWOULDBLOCK : EINTR);
710 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
711 } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
713 if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
714 VFS_MarkFull(Node, 1);
718 void PTY_CloseServer(tVFS_Node *Node)
720 tPTY *pty = Node->ImplPtr;
722 Node->ReferenceCount --;
723 // If reference count == 0, remove from main list
724 if( Node->ReferenceCount > 0 )
727 // Locate on list and remove
729 if( pty->NumericName == -1 ) {
730 RWLock_AcquireWrite(&glPTY_NamedPTYs);
731 prev_np = &gpPTY_FirstNamedPTY;
734 RWLock_AcquireWrite(&glPTY_NumPTYs);
735 prev_np = &gpPTY_FirstNumPTY;
738 // Search list until *prev_np is equal to pty
739 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
743 if( *prev_np != pty ) {
744 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
747 *prev_np = pty->Next;
751 if( pty->NumericName == -1 ) {
752 RWLock_Release(&glPTY_NamedPTYs);
756 RWLock_Release(&glPTY_NumPTYs);
760 // Send SIGHUP to controling PGID
761 if( pty->ControllingProcGroup > 0 ) {
762 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
765 // If there are no open children, we can safely free this PTY
766 if( pty->ClientNode.ReferenceCount == 0 ) {
772 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
774 tPTY *pty = Node->ImplPtr;
775 struct ptymode *mode = Data;
776 struct ptydims *dims = Data;
778 int is_server = !pty || Node == pty->ServerNode;
782 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
783 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
784 case DRV_IOCTL_VERSION: return 0x100;
785 case DRV_IOCTL_LOOKUP: return 0;
787 case PTY_IOCTL_GETMODE:
789 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
791 // TODO: ACK client's SETMODE
793 case PTY_IOCTL_SETMODE:
795 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
796 PTY_SetAttrib(pty, NULL, mode, !is_server);
798 case PTY_IOCTL_GETDIMS:
800 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
803 case PTY_IOCTL_SETDIMS:
805 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
806 PTY_SetAttrib(pty, dims, NULL, !is_server);
808 case PTY_IOCTL_GETID:
811 size_t len = strlen(pty->Name)+1;
814 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
815 strcpy(Data, pty->Name);
820 case PTY_IOCTL_SETID:
821 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
822 if( pty ) return EALREADY;
823 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
827 pty->ServerNode = Node;
829 case PTY_IOCTL_SETPGRP:
830 // TODO: Should this only be done by client?
833 if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
834 pty->ControllingProcGroup = *(tPGID*)Data;
835 Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
837 return pty->ControllingProcGroup;