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];
52 tVFS_Node *ServerNode;
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);
64 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
65 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
66 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
67 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
69 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
70 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
71 void PTY_ReferenceClient(tVFS_Node *Node);
72 void PTY_CloseClient(tVFS_Node *Node);
73 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
74 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
75 void PTY_CloseServer(tVFS_Node *Node);
76 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
79 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
80 tVFS_NodeType gPTY_NodeType_Root = {
81 .TypeName = "PTY-Root",
82 .ReadDir = PTY_ReadDir,
83 .FindDir = PTY_FindDir,
85 tVFS_NodeType gPTY_NodeType_Client = {
86 .TypeName = "PTY-Client",
87 .Read = PTY_ReadClient,
88 .Write = PTY_WriteClient,
90 .Reference = PTY_ReferenceClient,
91 .Close = PTY_CloseClient
93 tVFS_NodeType gPTY_NodeType_Server = {
94 .TypeName = "PTY-Server",
95 .Read = PTY_ReadServer,
96 .Write = PTY_WriteServer,
98 .Close = PTY_CloseServer
100 tDevFS_Driver gPTY_Driver = {
103 .Flags = VFS_FFLAG_DIRECTORY,
104 .Type = &gPTY_NodeType_Root,
109 tRWLock glPTY_NumPTYs;
110 tPTY *gpPTY_FirstNumPTY;
111 int giPTY_NamedCount;
112 tRWLock glPTY_NamedPTYs;
113 tPTY *gpPTY_FirstNamedPTY;
116 int PTY_Install(char **Arguments)
118 DevFS_AddDevice(&gPTY_Driver);
119 return MODULE_ERR_OK;
122 // --- Management ---
123 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet)
125 tPTY **prev_np = NULL;
128 if( Name && Name[0] )
130 prev_np = &gpPTY_FirstNamedPTY;
132 // Check the name isn't decimal
134 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
139 RWLock_AcquireWrite(&glPTY_NamedPTYs);
141 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
143 int cmp = strcmp(pty->Name, Name);
147 RWLock_Release(&glPTY_NamedPTYs);
153 namelen = strlen(Name);
158 RWLock_AcquireWrite(&glPTY_NumPTYs);
159 // Get a pty ID if Name==NULL
160 prev_np = &gpPTY_FirstNumPTY;
161 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
163 if( pty->NumericName > idx )
167 namelen = snprintf(NULL,0, "%u", idx);
170 tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
176 // - List maintainance
177 ret->Next = *prev_np;
179 // - PTY Name (Used by VT)
180 ret->Name = (char*)(ret + 1);
182 strcpy(ret->Name, Name);
184 sprintf(ret->Name, "%u", idx);
185 ret->NumericName = idx;
186 // - Output function and handle (same again)
187 ret->OutputHandle = Handle;
188 ret->OutputFcn = Output;
189 ret->ReqResize = ReqResize;
190 ret->ModeSet = ModeSet;
192 ret->ClientNode.ImplPtr = ret;
193 ret->ClientNode.Type = &gPTY_NodeType_Client;
194 ret->ClientNode.UID = Threads_GetUID();
195 ret->ClientNode.GID = Threads_GetGID();
196 ret->ClientNode.NumACLs = 1;
197 ret->ClientNode.ACLs = &ret->OwnerRW;
198 // - Owner Read-Write ACL
199 ret->OwnerRW.Ent.ID = Threads_GetUID();
200 ret->OwnerRW.Perm.Perms = -1;
202 if( Name && Name[0] ) {
204 RWLock_Release(&glPTY_NamedPTYs);
208 RWLock_Release(&glPTY_NumPTYs);
214 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
218 // (for now) userland terminals can't be put into framebuffer mode
219 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
225 if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
230 else if( !PTY->OutputFcn )
232 Log_Warning("PTY", "TODO: Need to stop client output until modeset has been ACKed");
233 // Block write until acked
234 // ACK by server doing GETMODE
239 // Should the client be informed that the server just twiddled the modes?
241 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
249 if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
254 else if( !PTY->OutputFcn )
256 // Inform server process... somehow
261 // SIGWINSZ to client
263 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
269 void PTY_Close(tPTY *PTY)
274 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
276 size_t space = (*rd - *wr + buflen - 1) % buflen;
277 ENTER("pbuf ibuflen prd pwr pdata ilen", buf, buflen, rd, wr, data, len);
278 len = MIN(space, len);
279 LOG("space = %i, *rd = %i, *wr = %i", space, *rd, *wr);
280 if(*wr + len >= buflen) {
281 size_t prelen = buflen - *wr;
282 memcpy((char*)buf + *wr, data, prelen);
283 memcpy(buf, (char*)data + prelen, len - prelen);
287 memcpy((char*)buf + *wr, data, len);
293 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
295 size_t space = (*wr - *rd + buflen) % buflen;
296 len = MIN(space, len);
297 if(*rd + len >= buflen) {
298 size_t prelen = buflen - *rd;
299 memcpy(data, (char*)buf + *rd, prelen);
300 memcpy((char*)data + prelen, buf, len - prelen);
304 memcpy(data, (char*)buf + *rd, len);
310 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
314 Mutex_Acquire(&PTY->InputMutex);
316 ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
319 Mutex_Release(&PTY->InputMutex);
321 VFS_MarkAvaliable(&PTY->ClientNode, 1);
323 VFS_MarkFull(PTY->ServerNode, 1);
328 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
330 size_t ret = 1, print = 1;
332 // Input mode stuff only counts for text output mode
333 // - Any other is Uint32 keypresses
334 if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
335 return PTY_int_WriteInput(PTY, Input, Length);
336 // If in raw mode, flush directlr
337 if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
338 return PTY_int_WriteInput(PTY, Input, Length);
340 if( PTY->Mode.InputMode & PTYIMODE_CANON )
342 const char char_bs = '\b';
347 // Threads_PostSignalExt(PTY->ClientThreads, SIGINT);
351 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
352 PTY->HasHitEOF = (PTY->LineLength == 0);
357 if(PTY->LineLength != 0)
360 case 'w'-'a': // Word erase
361 while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
362 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
365 case 'u'-'a': // Kill
366 while(PTY->LineLength > 0)
367 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
377 if(PTY->LineLength == INPUT_LINE_LEN) {
378 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
381 PTY->LineData[PTY->LineLength++] = '\n';
382 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
385 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
390 if(PTY->LineLength == INPUT_LINE_LEN) {
391 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
394 PTY->LineData[PTY->LineLength++] = Input[0];
400 ret = PTY_int_WriteInput(PTY, Input, Length);
404 if( PTY->Mode.InputMode & PTYIMODE_ECHO )
406 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
412 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
415 while( ret < Length && !PTY->ClientNode.BufferFull )
417 // TODO: Detect blocking?
418 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
424 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
428 if( idx < giPTY_NumCount )
430 RWLock_AcquireRead(&glPTY_NumPTYs);
431 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
433 RWLock_Release(&glPTY_NumPTYs);
435 else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
437 idx -= giPTY_NumCount;
438 RWLock_AcquireRead(&glPTY_NamedPTYs);
439 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
441 RWLock_Release(&glPTY_NamedPTYs);
445 LOG("%i out of range", Pos);
449 strncpy(Name, pty->Name, FILENAME_MAX)
450 LOG("Return '%s'", Name);
454 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
457 int num = strtol(Name, &end, 10);
459 if( strcmp(Name, "ptmx") == 0 ) {
460 tVFS_Node *ret = calloc(sizeof(tVFS_Node), 1);
462 ret->Type = &gPTY_NodeType_Server;
466 if( Name[0] == '\0' )
470 if( num && end[0] == '\0' )
473 RWLock_AcquireRead(&glPTY_NumPTYs);
474 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
476 if( pty->NumericName > num )
478 if( pty->NumericName == num ) {
483 RWLock_Release(&glPTY_NumPTYs);
488 RWLock_AcquireRead(&glPTY_NamedPTYs);
489 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
491 int cmp = strcmp(pty->Name, Name);
499 RWLock_Release(&glPTY_NamedPTYs);
502 tVFS_Node *retnode = &ret->ClientNode;
503 retnode->ReferenceCount ++;
510 //\! Read from the client's input
511 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
513 tPTY *pty = Node->ImplPtr;
515 // Read from flushed queue
516 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
519 // If server has disconnected, return EIO
520 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
521 //Threads_PostSignal(SIGPIPE);
525 // Wait for data to be ready
526 rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
528 errno = (timeout ? EWOULDBLOCK : EINTR);
532 Mutex_Acquire(&pty->InputMutex);
533 Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
535 Mutex_Release(&pty->InputMutex);
537 if(pty->InputReadPos == pty->InputWritePos)
538 VFS_MarkAvaliable(Node, 0);
540 if(Length == 0 && !pty->HasHitEOF) {
548 //\! Write to the client's output
549 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
551 tPTY *pty = Node->ImplPtr;
553 // If the server has terminated, send SIGPIPE
554 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
556 //Threads_PostSignal(SIGPIPE);
561 // Write to either FIFO or directly to output function
564 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
568 // Write to output ringbuffer
569 Length = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
570 &pty->OutputReadPos, &pty->OutputWritePos,
572 VFS_MarkAvaliable(pty->ServerNode, 1);
578 void PTY_ReferenceClient(tVFS_Node *Node)
580 Node->ReferenceCount ++;
581 // TODO: Add PID to list of client PIDs
582 // Log_Notice("PTY", "ReferenceClient: TODO - List of client PIDs");
585 void PTY_CloseClient(tVFS_Node *Node)
587 tPTY *pty = Node->ImplPtr;
588 Node->ReferenceCount --;
590 // Remove PID from list
591 // TODO: Maintain list of client processes
593 // Free structure if this was the last open handle
594 if( Node->ReferenceCount > 0 )
596 if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
598 // Free the structure! (Should be off the PTY list now)
599 free(pty->ServerNode);
604 //\! Read from the client's output
605 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
607 tPTY *pty = Node->ImplPtr;
609 // TODO: Prevent two servers fighting over client's output
612 // Kernel-land PTYs can't be read from userland
616 // Read back from fifo
617 tTime timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
618 int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
620 errno = (timeout ? EWOULDBLOCK : EINTR);
624 Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
625 &pty->OutputReadPos, &pty->OutputWritePos,
627 if( pty->OutputReadPos == pty->OutputWritePos )
628 VFS_MarkAvaliable(Node, 0);
629 VFS_MarkFull(&pty->ClientNode, 0);
634 //\! Write to the client's input
635 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
637 return PTY_SendInput(Node->ImplPtr, Buffer, Length);
640 void PTY_CloseServer(tVFS_Node *Node)
642 tPTY *pty = Node->ImplPtr;
644 Node->ReferenceCount --;
645 // If reference count == 0, remove from main list
646 if( Node->ReferenceCount > 0 )
649 // Locate on list and remove
651 if( pty->NumericName == 0 ) {
652 RWLock_AcquireWrite(&glPTY_NamedPTYs);
653 prev_np = &gpPTY_FirstNamedPTY;
656 RWLock_AcquireWrite(&glPTY_NumPTYs);
657 prev_np = &gpPTY_FirstNumPTY;
660 // Search list until *prev_np is equal to pty
661 for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
665 if( *prev_np != pty ) {
666 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
669 *prev_np = pty->Next;
673 if( pty->NumericName == 0 ) {
674 RWLock_Release(&glPTY_NamedPTYs);
678 RWLock_Release(&glPTY_NumPTYs);
682 // If there are no open children, we can safely free this PTY
683 if( pty->ClientNode.ReferenceCount == 0 ) {
689 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
691 tPTY *pty = Node->ImplPtr;
692 struct ptymode *mode = Data;
693 struct ptydims *dims = Data;
695 int is_server = !pty || Node == pty->ServerNode;
699 case DRV_IOCTL_TYPE: return DRV_TYPE_TERMINAL;
700 case DRV_IOCTL_IDENT: memcpy(Data, "PTY\0", 4); return 0;
701 case DRV_IOCTL_VERSION: return 0x100;
702 case DRV_IOCTL_LOOKUP: return 0;
704 case PTY_IOCTL_GETMODE:
706 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
708 // TODO: ACK client's SETMODE
710 case PTY_IOCTL_SETMODE:
712 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
713 PTY_SetAttrib(pty, NULL, mode, !is_server);
715 case PTY_IOCTL_GETDIMS:
717 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
720 case PTY_IOCTL_SETDIMS:
722 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
723 PTY_SetAttrib(pty, dims, NULL, !is_server);
725 case PTY_IOCTL_GETID:
728 size_t len = strlen(pty->Name)+1;
731 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
732 strcpy(Data, pty->Name);
737 case PTY_IOCTL_SETID:
738 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
739 if( pty ) return EALREADY;
740 pty = PTY_Create(Data, NULL, NULL,NULL, NULL);
744 pty->ServerNode = Node;