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
111 tRWLock glPTY_NumPTYs;
112 tPTY *gpPTY_FirstNumPTY;
113 int giPTY_NamedCount;
114 tRWLock glPTY_NamedPTYs;
115 tPTY *gpPTY_FirstNamedPTY;
118 int PTY_Install(char **Arguments)
120 DevFS_AddDevice(&gPTY_Driver);
121 return MODULE_ERR_OK;
124 // --- Management ---
125 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
127 tPTY **prev_np = NULL;
130 if( Name && Name[0] )
132 prev_np = &gpPTY_FirstNamedPTY;
134 // Check the name isn't decimal
136 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
141 RWLock_AcquireWrite(&glPTY_NamedPTYs);
143 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
145 int cmp = strcmp(pty->Name, Name);
149 RWLock_Release(&glPTY_NamedPTYs);
155 namelen = strlen(Name);
160 RWLock_AcquireWrite(&glPTY_NumPTYs);
161 // Get a pty ID if Name==NULL
162 prev_np = &gpPTY_FirstNumPTY;
163 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
165 if( pty->NumericName > idx )
172 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
178 // - List maintainance
179 ret->Next = *prev_np;
181 // - PTY Name (Used by VT)
182 ret->Name = (char*)(ret + 1);
184 strcpy(ret->Name, Name);
187 ret->NumericName = idx;
188 // - Output function and handle (same again)
189 ret->OutputHandle = Handle;
190 ret->OutputFcn = Output;
191 ret->ReqResize = ReqResize;
192 ret->ModeSet = ModeSet;
194 ret->ServerNode.ImplPtr = ret;
195 ret->ServerNode.Type = &gPTY_NodeType_Server;
196 ret->ServerNode.UID = Threads_GetUID();
197 ret->ServerNode.GID = Threads_GetGID();
198 ret->ServerNode.NumACLs = 1;
199 ret->ServerNode.ACLs = &ret->OwnerRW;
200 ret->ServerNode.ReferenceCount = (Output ? 1 : 0); // Prevent a userland close killing a kernel pty
202 ret->ClientNode.ImplPtr = ret;
203 ret->ClientNode.Type = &gPTY_NodeType_Client;
204 ret->ClientNode.UID = Threads_GetUID();
205 ret->ClientNode.GID = Threads_GetGID();
206 ret->ClientNode.NumACLs = 1;
207 ret->ClientNode.ACLs = &ret->OwnerRW;
208 // - Owner Read-Write ACL
209 ret->OwnerRW.Ent.ID = Threads_GetUID();
210 ret->OwnerRW.Perm.Perms = -1;
212 if( Name && Name[0] ) {
214 RWLock_Release(&glPTY_NamedPTYs);
218 RWLock_Release(&glPTY_NumPTYs);
224 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
228 // (for now) userland terminals can't be put into framebuffer mode
229 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
235 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
240 else if( !PTY->OutputFcn )
242 Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
243 // Block write until acked
244 // ACK by server doing GETMODE
249 // Should the client be informed that the server just twiddled the modes?
251 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
259 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
264 else if( !PTY->OutputFcn )
266 // Inform server process... somehow
271 // SIGWINSZ to client
273 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
279 void PTY_Close(tPTY *PTY)
284 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
286 size_t space = (*rd - *wr + buflen - 1) % buflen;
287 ENTER("pbuf ibuflen prd pwr pdata ilen", buf, buflen, rd, wr, data, len);
288 len = MIN(space, len);
289 LOG("space = %i, *rd = %i, *wr = %i", space, *rd, *wr);
290 if(*wr + len >= buflen) {
291 size_t prelen = buflen - *wr;
292 memcpy((char*)buf + *wr, data, prelen);
293 memcpy(buf, (char*)data + prelen, len - prelen);
297 memcpy((char*)buf + *wr, data, len);
303 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
305 size_t space = (*wr - *rd + buflen) % buflen;
306 len = MIN(space, len);
307 if(*rd + len >= buflen) {
308 size_t prelen = buflen - *rd;
309 memcpy(data, (char*)buf + *rd, prelen);
310 memcpy((char*)data + prelen, buf, len - prelen);
314 memcpy(data, (char*)buf + *rd, len);
320 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
324 Mutex_Acquire(&PTY->InputMutex);
326 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
329 Mutex_Release(&PTY->InputMutex);
331 VFS_MarkAvaliable(&PTY->ClientNode, 1);
333 VFS_MarkFull(&PTY->ServerNode, 1);
338 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
340 size_t ret = 1, print = 1;
342 // Input mode stuff only counts for text output mode
343 // - Any other is Uint32 keypresses
344 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
345 return PTY_int_WriteInput(PTY, Input, Length);
346 // If in raw mode, flush directlr
347 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
348 return PTY_int_WriteInput(PTY, Input, Length);
350 if( PTY->Mode.InputMode & PTYIMODE_CANON )
352 const char char_bs = '\b';
357 // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
361 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
362 PTY->HasHitEOF = (PTY->LineLength == 0);
367 if(PTY->LineLength != 0)
370 case 'w'-'a': // Word erase
371 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
372 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
375 case 'u'-'a': // Kill
376 while(PTY->LineLength > 0)
377 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
387 if(PTY->LineLength == INPUT_LINE_LEN) {
388 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
391 PTY->LineData[PTY->LineLength++] = '\n';
392 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
395 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
400 if(PTY->LineLength == INPUT_LINE_LEN) {
401 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
404 PTY->LineData[PTY->LineLength++] = Input[0];
410 ret = PTY_int_WriteInput(PTY, Input, Length);
414 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
416 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
422 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
425 while( ret < Length && !PTY->ClientNode.BufferFull )
427 // TODO: Detect blocking?
428 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
434 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
437 if( Pos < giPTY_NumCount * 2 )
439 RWLock_AcquireRead(&glPTY_NumPTYs);
440 for( pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
446 RWLock_Release(&glPTY_NumPTYs);
448 else if( Pos < (giPTY_NumCount + giPTY_NamedCount) * 2 )
450 RWLock_AcquireRead(&glPTY_NamedPTYs);
451 for( pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
457 RWLock_Release(&glPTY_NamedPTYs);
465 snprintf(Name, FILENAME_MAX, "%s%c", pty->Name, (Pos == 0 ? 'c' : 's'));
467 snprintf(Name, FILENAME_MAX, "%i%c", pty->NumericName, (Pos == 0 ? 'c' : 's'));
471 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
474 int num = strtol(Name, &end, 10);
476 if( Name[0] == '\0' || Name[1] == '\0' )
479 size_t len = strlen(Name);
480 if( Name[len-1] != 'c' && Name[len-1] != 's' )
482 int isServer = (Name[len-1] != 'c');
485 if( num && (end[0] == 'c' || end[0] == 's') && end[1] == '\0' )
488 RWLock_AcquireRead(&glPTY_NumPTYs);
489 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
491 if( pty->NumericName > num )
493 if( pty->NumericName == num ) {
498 RWLock_Release(&glPTY_NumPTYs);
503 RWLock_AcquireRead(&glPTY_NamedPTYs);
504 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
506 int cmp = strncmp(pty->Name, Name, len-1);
509 if(cmp == 0 && pty->Name[len-1] == '\0' ) {
514 RWLock_Release(&glPTY_NamedPTYs);
517 return (isServer ? &ret->ServerNode : &ret->ClientNode);
522 tVFS_Node *PTY_MkNod(tVFS_Node *Node, const char *Name, Uint Mode)
524 // zero-length name means a numbered pty has been requested
525 if( Name[0] == '\0' || (Name[0] == '#' && Name[1] == '\0') )
527 tPTY *ret = PTY_Create(NULL, NULL, NULL, NULL, NULL);
530 return &ret->ServerNode;
533 // Otherwise return a named PTY
534 // TODO: Should the request be for '<name>s' or just '<name>'
536 tPTY *ret = PTY_Create(Name, NULL, NULL, NULL, NULL);
539 return &ret->ServerNode;
542 //\! Read from the client's input
543 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
545 tPTY *pty = Node->ImplPtr;
547 // Read from flushed queue
548 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
551 // If server has disconnected, return EIO
552 if( pty->ServerNode.ReferenceCount == 0 ) {
553 //Threads_PostSignal(SIGPIPE);
557 // Wait for data to be ready
558 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
560 errno = (timeout ? EWOULDBLOCK : EINTR);
564 Mutex_Acquire(&pty->InputMutex);
565 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
567 Mutex_Release(&pty->InputMutex);
569 if(pty->InputReadPos == pty->InputWritePos)
570 VFS_MarkAvaliable(Node, 0);
572 if(Length == 0 && !pty->HasHitEOF) {
580 //\! Write to the client's output
581 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
583 tPTY *pty = Node->ImplPtr;
585 // If the server has terminated, send SIGPIPE
586 if( pty->ServerNode.ReferenceCount == 0 )
588 //Threads_PostSignal(SIGPIPE);
593 // Write to either FIFO or directly to output function
596 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
600 // Write to output ringbuffer
601 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
602 &pty->OutputReadPos, &pty->OutputWritePos,
604 VFS_MarkAvaliable(&pty->ServerNode, 1);
610 int PTY_IOCtlClient(tVFS_Node *Node, int ID, void *Data)
612 tPTY *pty = Node->ImplPtr;
613 struct ptymode *mode = Data;
614 struct ptydims *dims = Data;
617 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
618 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
619 case DRV_IOCTL_VERSION: return 0x100;
620 case DRV_IOCTL_LOOKUP: return 0;
622 case PTY_IOCTL_GETMODE:
623 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
626 case PTY_IOCTL_SETMODE:
627 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
628 return PTY_SetAttrib(pty, NULL, mode, 1);
629 case PTY_IOCTL_GETDIMS:
630 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
633 case PTY_IOCTL_SETDIMS:
634 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
635 return PTY_SetAttrib(pty, dims, NULL, 1);
641 void PTY_ReferenceClient(tVFS_Node *Node)
643 Node->ReferenceCount ++;
644 // TODO: Add PID to list of client PIDs
645 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
648 void PTY_CloseClient(tVFS_Node *Node)
650 tPTY *pty = Node->ImplPtr;
651 Node->ReferenceCount --;
653 // Remove PID from list
654 // TODO: Maintain list of client processes
656 // Free structure if this was the last open handle
657 if( Node->ReferenceCount == 0 && pty->ServerNode.ReferenceCount == 0 )
659 // Free the structure! (Should be off the PTY list now)
664 //\! Read from the client's output
665 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
667 tPTY *pty = Node->ImplPtr;
669 // TODO: Prevent two servers fighting over client's output
672 // Kernel-land PTYs can't be read from userland
676 // Read back from fifo
677 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
678 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
680 errno = (timeout ? EWOULDBLOCK : EINTR);
684 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
685 &pty->OutputReadPos, &pty->OutputWritePos,
687 if( pty->OutputReadPos == pty->OutputWritePos )
688 VFS_MarkAvaliable(Node, 0);
689 VFS_MarkFull(&pty->ClientNode, 0);
694 //\! Write to the client's input
695 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
697 return PTY_SendInput(Node->ImplPtr, Buffer, Length);
700 int PTY_IOCtlServer(tVFS_Node *Node, int ID, void *Data)
702 tPTY *pty = Node->ImplPtr;
703 struct ptymode *mode = Data;
704 struct ptydims *dims = Data;
707 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
708 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
709 case DRV_IOCTL_VERSION: return 0x100;
710 case DRV_IOCTL_LOOKUP: return 0;
712 case PTY_IOCTL_GETMODE:
713 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
715 // ACK client's SETMODE
717 case PTY_IOCTL_SETMODE:
718 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
719 PTY_SetAttrib(pty, NULL, mode, 0);
721 case PTY_IOCTL_GETDIMS:
722 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
725 case PTY_IOCTL_SETDIMS:
726 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
727 PTY_SetAttrib(pty, dims, NULL, 0);
729 case PTY_IOCTL_GETID:
730 return pty->NumericName;
736 void PTY_CloseServer(tVFS_Node *Node)
738 tPTY *pty = Node->ImplPtr;
740 Node->ReferenceCount --;
741 // If reference count == 0, remove from main list
742 if( Node->ReferenceCount > 0 )
745 // Locate on list and remove
748 RWLock_AcquireWrite(&glPTY_NamedPTYs);
749 prev_np = &gpPTY_FirstNamedPTY;
752 RWLock_AcquireWrite(&glPTY_NumPTYs);
753 prev_np = &gpPTY_FirstNumPTY;
756 // Search list until *prev_np is equal to pty
757 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
761 if( *prev_np != pty ) {
762 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
765 *prev_np = pty->Next;
770 RWLock_Release(&glPTY_NamedPTYs);
774 RWLock_Release(&glPTY_NumPTYs);
778 // If there are no open children, we can safely free this PTY
779 if( pty->ClientNode.ReferenceCount == 0 )