2018年7月17日 星期二

TLPI: DAEMONS Overview

daemon 是有下列特性的 process:
  • 常駐的。通常在系統起始時建立,運作到系統結束。
  • 背景執行,且沒有控制終端機。由於缺乏終端機,要確保 kernel 不會自動生任何 job 控制或終端相關 signals (如 SIGINT、SIGTSTP、SIGHUP) 給 daemon。
daemon 用來執行特定工作,例如:
  • cron:在排定的時間執行指令。
  • sshd:使用 secure communication protocol 遠端登入的 secure shell daemon。
  • httpd:HTTP 伺服器 daemon,提供網頁。
  • inetd:Internet 超級伺服器 daemon (見 TLPI §60.5),在特定 TCP/IP 埠等待網路連線,啟動對應的伺服器程式處理。
daemon 常習慣取名以子母 d 為結尾。

許多標準 daemon 是特權行程 (也就是 effective user ID 是 0),因此應該依照 TLPI §38 的準則撰寫。

在 Linux,有些 daemon 是 kernel thread,是 kernel 的一部分。當用 ps 指令列出時,名稱會用 [] 包起來,例如 [pdflush],週期 flushes dirty pages 到硬碟。

參考來源:TLPI §37.1

The Linux Programming Interface

不錯的 Linux 書,2010 十月出版,作者 Michael Kerrisk 是 Linux man-pages 的維護者而許多內容類似。
官網:http://man7.org/tlpi/
章節:http://man7.org/tlpi/toc-detailed.html
PREFACE
1 HISTORY AND STANDARDS
1.1 A Brief History of UNIX and C
1.2 A Brief History of Linux
1.2.1 The GNU Project
1.2.2 The Linux Kernel
1.3 Standardization
1.3.1 The C Programming Language
1.3.2 The First POSIX Standards
1.3.3 X/Open Company and The Open Group
1.3.4 SUSv3 and POSIX.1-2001
1.3.5 SUSv4 and POSIX.1-2008
1.3.6 UNIX Standards Timeline
1.3.7 Implementation Standards
1.3.8 Linux, Standards, and the Linux Standard Base
1.4 Summary

2 FUNDAMENTAL CONCEPTS
2.1 The Core Operating System: The Kernel
2.2 The Shell
2.3 Users and Groups
2.4 Single Directory Hierarchy, Directories, Links, and Files
2.5 File I/O Model
2.6 Programs
2.7 Processes
2.8 Memory Mappings
2.9 Static and Shared Libraries
2.10 Interprocess Communication and Synchronization
2.11 Signals
2.12 Threads
2.13 Process Groups and Shell Job Control
2.14 Sessions, Controlling Terminals, and Controlling Processes
2.15 Pseudoterminals
2.16 Date and Time (https://lirobo.blogspot.com/2014/12/linux-time.html)
2.17 Client-Server Architecture
2.18 Realtime (https://lirobo.blogspot.com/2014/12/linux-time.html)
2.19 The /proc File System
2.20 Summary

3 SYSTEM PROGRAMMING CONCEPTS
3.1 System Calls
3.2 Library Functions
3.3 The Standard C Library; The GNU C Library (glibc)
3.4 Handling Errors from System Calls and Library Functions
3.5 Notes on the Example Programs in This Book
3.5.1 Command-Line Options and Arguments
3.5.2 Common Functions and Header Files
3.6 Portability Issues
3.6.1 Feature Test Macros
3.6.2 System Data Types
3.6.3 Miscellaneous Portability Issues
3.7 Summary
3.8 Exercise

4 FILE I/O: THE UNIVERSAL I/O MODEL
5 FILE I/O: FURTHER DETAILS

6 PROCESSES
6.1 Processes and Programs
6.2 Process ID and Parent Process ID
6.3 Memory Layout of a Process
6.4 Virtual Memory Management
6.5 The Stack and Stack Frames
6.6 Command-Line Arguments (argc, argv)
6.7 Environment List
6.8 Performing a Nonlocal Goto: setjmp() and longjmp()
6.9 Summary
6.10 Exercises

7 MEMORY ALLOCATION

8 USERS AND GROUPS
8.1 The Password File: /etc/passwd
8.2 The Shadow Password File: /etc/shadow
8.3 The Group File: /etc/group
8.4 Retrieving User and Group Information
8.5 Password Encryption and User Authentication
8.6 Summary
8.7 Exercises

9 PROCESS CREDENTIALS
9.1 Real User ID and Real Group ID
9.2 Effective User ID and Effective Group ID
9.3 Set-User-ID and Set-Group-ID Programs
9.4 Saved Set-User-ID and Saved Set-Group-ID
9.5 File-System User ID and File-System Group ID
9.6 Supplementary Group IDs
9.7 Retrieving and Modifying Process Credentials
9.7.1 Retrieving and Modifying Real, Effective, and Saved Set IDs
9.7.2 Retrieving and Modifying File-System IDs
9.7.3 Retrieving and Modifying Supplementary Group IDs
9.7.4 Summary of Calls for Modifying Process Credentials
9.7.5 Example: Displaying Process Credentials
9.8 Summary
9.9 Exercises

10 TIME
10.2.3 Converting Between Broken-Down Time and Printable Form
10.3 Timezones
10.4 Locales
10.5 Updating the System Clock
10.6 The Software Clock (Jiffies)
10.7 Process Time
10.8 Summary
10.9 Exercise

11 SYSTEM LIMITS AND OPTIONS
11.1 System Limits
11.2 Retrieving System Limits (and Options) at Run Time
11.3 Retrieving File-Related Limits (and Options) at Run Time
11.4 Indeterminate Limits
11.5 System Options
11.6 Summary
11.7 Exercises

12 SYSTEM AND PROCESS INFORMATION
12.1 The /proc File System
12.1.1 Obtaining Information About a Process: /proc/PID
12.1.2 System Information Under /proc
12.1.3 Accessing /proc Files
12.2 System Identification: uname()
12.3 Summary
12.4 Exercises

13 FILE I/O BUFFERING
13.1 Kernel Buffering of File I/O: The Buffer Cache
13.2 Buffering in the stdio Library
13.3 Controlling Kernel Buffering of File I/O
13.4 Summary of I/O Buffering
13.5 Giving the Kernel Hints About I/O Patterns: posix_fadvise()
13.6 Bypassing the Buffer Cache: Direct I/O
13.7 Mixing Library Functions and System Calls for File I/O
13.8 Summary
13.9 Exercises

14 FILE SYSTEMS
14.1 Device Special Files (Devices)
14.2 Disks and Partitions
14.3 File Systems
14.4 I-nodes
14.5 The Virtual File System (VFS)
14.6 Journaling File Systems
14.7 Single Directory Hierarchy and Mount Points
14.8 Mounting and Unmounting File Systems
14.8.1 Mounting a File System: mount()
14.8.2 Unmounting a File System: umount() and umount2()
14.9 Advanced Mount Features
14.9.1 Mounting a File System at Multiple Mount Points
14.9.2 Stacking Multiple Mounts on the Same Mount Point
14.9.3 Mount Flags That Are Per-Mount Options
14.9.4 Bind Mounts
14.9.5 Recursive Bind Mounts
14.10 A Virtual Memory File System: tmpfs
14.11 Obtaining Information About a File System: statvfs()
14.12 Summary
14.13 Exercise

15 FILE ATTRIBUTES
15.1 Retrieving File Information: stat()
15.2 File Timestamps
15.2.1 Changing File Timestamps with utime() and utimes()
15.2.2 Changing File Timestamps with utimensat() and futimens()
15.3 File Ownership
15.3.1 Ownership of New Files
15.3.2 Changing File Ownership: chown(), fchown(), and lchown()
15.4 File Permissions
15.4.1 Permissions on Regular Files
15.4.2 Permissions on Directories
15.4.3 Permission-Checking Algorithm
15.4.4 Checking File Accessibility: access()
15.4.5 Set-User-ID, Set-Group-ID, and Sticky Bits
15.4.6 The Process File Mode Creation Mask: umask()
15.4.7 Changing File Permissions: chmod() and fchmod()
15.5 I-node Flags (ext2 Extended File Attributes)
15.6 Summary
15.7 Exercises

16 EXTENDED ATTRIBUTES
16.1 Overview
16.2 Extended Attribute Implementation Details
16.3 System Calls for Manipulating Extended Attributes
16.4 Summary
16.5 Exercise

17 ACCESS CONTROL LISTS
17.1 Overview
17.2 ACL Permission-Checking Algorithm
17.3 Long and Short Text Forms for ACLs
17.4 The ACL_MASK Entry and the ACL Group Class
17.5 The getfacl and setfacl Commands
17.6 Default ACLs and File Creation
17.7 ACL Implementation Limits
17.8 The ACL API
17.9 Summary
17.10 Exercise

18 DIRECTORIES AND LINKS
18.1 Directories and (Hard) Links
18.2 Symbolic (Soft) Links
18.3 Creating and Removing (Hard) Links: link() and unlink()
18.4 Changing the Name of a File: rename()
18.5 Working with Symbolic Links: symlink() and readlink()
18.6 Creating and Removing Directories: mkdir() and rmdir()
18.7 Removing a File or Directory: remove()
18.8 Reading Directories: opendir() and readdir()
18.9 File Tree Walking: nftw()
18.10 The Current Working Directory of a Process
18.11 Operating Relative to a Directory File Descriptor
18.12 Changing the Root Directory of a Process: chroot()
18.13 Resolving a Pathname: realpath()
18.14 Parsing Pathname Strings: dirname() and basename()
18.15 Summary
18.16 Exercises

19 MONITORING FILE EVENTS
19.1 Overview
19.2 The inotify API
19.3 inotify Events
19.4 Reading inotify Events
19.5 Queue Limits and /proc Files
19.6 An Older System for Monitoring File Events: dnotify
19.7 Summary
19.8 Exercise

20 SIGNALS: FUNDAMENTAL CONCEPTS
20.1 Concepts and Overview
20.2 Signal Types and Default Actions
20.3 Changing Signal Dispositions: signal()
20.4 Introduction to Signal Handlers
20.5 Sending Signals: kill()
20.6 Checking for the Existence of a Process
20.7 Other Ways of Sending Signals: raise() and killpg()
20.8 Displaying Signal Descriptions
20.9 Signal Sets
20.10 The Signal Mask (Blocking Signal Delivery)
20.11 Pending Signals
20.12 Signals Are Not Queued
20.13 Changing Signal Dispositions: sigaction()
20.14 Waiting for a Signal: pause()
20.15 Summary
20.16 Exercises

21 SIGNALS: SIGNAL HANDLERS
21.1 Designing Signal Handlers
21.1.1 Signals Are Not Queued (Revisited)
21.1.2 Reentrant and Async-Signal-Safe Functions
21.1.3 Global Variables and the sig_atomic_t Data Type
21.2 Other Methods of Terminating a Signal Handler
21.2.1 Performing a Nonlocal Goto from a Signal Handler
21.2.2 Terminating a Process Abnormally: abort()
21.3 Handling a Signal on an Alternate Stack: sigaltstack()
21.4 The SA_SIGINFO Flag
21.5 Interruption and Restarting of System Calls
21.6 Summary
21.7 Exercise

22 SIGNALS: ADVANCED FEATURES
22.1 Core Dump Files
22.2 Special Cases for Signal Delivery, Disposition, and Handling
22.3 Interruptible and Uninterruptible Process Sleep States
22.4 Hardware-Generated Signals
22.5 Synchronous and Asynchronous Signal Generation
22.6 Timing and Order of Signal Delivery
22.7 Implementation and Portability of signal()
22.8 Realtime Signals
22.8.1 Sending Realtime Signals
22.8.2 Handling Realtime Signals
22.9 Waiting for a Signal Using a Mask: sigsuspend()
22.10 Synchronously Waiting for a Signal
22.11 Fetching Signals via a File Descriptor
22.12 Interprocess Communication with Signals
22.13 Earlier Signal APIs (System V and BSD)
22.14 Summary
22.15 Exercises

23 TIMERS AND SLEEPING
23.1 Interval Timers
23.2 Scheduling and Accuracy of Timers
23.3 Setting Timeouts on Blocking Operations
23.4 Suspending Execution for a Fixed Interval (Sleeping)
23.4.1 Low-Resolution Sleeping: sleep()
23.4.2 High-Resolution Sleeping: nanosleep()
23.5 POSIX Clocks
23.5.1 Retrieving the Value of a Clock: clock_gettime()
23.5.2 Setting the Value of a Clock: clock_settime()
23.5.3 Obtaining the Clock ID of a Specific Process or Thread
23.5.4 Improved High-Resolution Sleeping: clock_nanosleep()
23.6 POSIX Interval Timers
23.6.1 Creating a Timer: timer_create()
23.6.2 Arming and Disarming a Timer: timer_settime()
23.6.3 Retrieving the Current Value of a Timer: timer_gettime()
23.6.4 Deleting a Timer: timer_delete()
23.6.5 Notification via a Signal
23.6.6 Timer Overruns
23.6.7 Notification via a Thread
23.7 Timers That Notify via File Descriptors: the timerfd API
23.8 Summary
23.9 Exercises

24 PROCESS CREATION
24.1 Overview of fork(), exit(), wait(), and execve()
24.2 Creating a New Process: fork()
24.2.1 File Sharing Between Parent and Child
24.2.2 Memory Semantics of fork()
24.3 The vfork() System Call
24.4 Race Conditions After fork()
24.5 Avoiding Race Conditions by Synchronizing with Signals
24.6 Summary

25 PROCESS TERMINATION
25.1 Terminating a Process: _exit() and exit()
25.2 Details of Process Termination
25.3 Exit Handlers
25.4 Interactions Between fork(), stdio Buffers, and _exit()
25.5 Summary
25.6 Exercise

26 MONITORING CHILD PROCESSES
26.1 Waiting on a Child Process
26.1.1 The wait() System Call
26.1.2 The waitpid() System Call
26.1.3 The Wait Status Value
26.1.4 Process Termination from a Signal Handler
26.1.5 The waitid() System Call
26.1.6 The wait3() and wait4() System Calls
26.2 Orphans and Zombies
26.3 The SIGCHLD Signal
26.3.1 Establishing a Handler for SIGCHLD
26.3.2 Delivery of SIGCHLD for Stopped Children
26.3.3 Ignoring Dead Child Processes
26.4 Summary
26.5 Exercises

27 PROGRAM EXECUTION
27.1 Executing a New Program: execve()
27.2 The exec() Library Functions
27.2.1 The PATH Environment Variable
27.2.2 Specifying Program Arguments As a List
27.2.3 Passing the Caller's Environment to the New Program
27.2.4 Executing a File Referred to by a Descriptor: fexecve()
27.3 Interpreter Scripts
27.4 File Descriptors and exec()
27.5 Signals and exec()
27.6 Executing a Shell Command: system()
27.7 Implementing system()
27.8 Summary
27.9 Exercises

28 PROCESS CREATION AND PROGRAM EXECUTION IN MORE DETAIL
28.1 Process Accounting
28.2 The clone() System Call
28.2.1 The clone() flags Argument
28.2.2 Extensions to waitpid() for Cloned Children
28.3 Speed of Process Creation
28.4 Effect of exec() and fork() on Process Attributes
28.5 Summary
28.6 Exercise

29 THREADS: INTRODUCTION
29.1 Overview
29.2 Background Details of the Pthreads API
29.3 Thread Creation
29.4 Thread Termination
29.5 Thread IDs
29.6 Joining with a Terminated Thread: pthread_join()
29.7 Detaching a Thread: pthread_detach()
29.8 Thread Attributes
29.9 Threads Versus Processes
29.10 Summary
29.11 Exercises

30 THREADS: THREAD SYNCHRONIZATION
30.1 Protecting Accesses to Shared Variables: Mutexes
30.1.1 Statically Allocated Mutexes
30.1.2 Locking and Unlocking a Mutex
30.1.3 Performance of Mutexes
30.1.4 Mutex Deadlocks
30.1.5 Dynamically Initializing a Mutex
30.1.6 Mutex Attributes
30.1.7 Mutex Types
30.2 Signaling Changes of State: Condition Variables
30.2.4 Example Program: Joining Any Terminated Thread
30.4 Exercises

31 THREADS: THREAD SAFETY AND PER-THREAD STORAGE
31.1 Thread Safety (and Reentrancy Revisited)
31.2 One-Time Initialization
31.3 Thread-Specific Data
31.3.1 Thread-Specific Data from the Library Function's Perspective
31.3.2 Overview of the Thread-Specific Data API
31.3.3 Details of the Thread-Specific Data API
31.3.4 Employing the Thread-Specific Data API
31.3.5 Thread-Specific Data Implementation Limits
31.4 Thread-Local Storage
31.5 Summary
31.6 Exercises

32 THREADS: THREAD CANCELLATION
32.1 Canceling a Thread
32.2 Cancellation State and Type
32.3 Cancellation Points
32.4 Testing for Thread Cancellation
32.5 Cleanup Handlers
32.6 Asynchronous Cancelability
32.7 Summary
32.8 Exercises

33 THREADS: FURTHER DETAILS
33.1 Thread Stacks
33.2 Threads and Signals
33.2.1 How the UNIX Signal Model Maps to Threads
33.2.2 Manipulating the Thread Signal Mask
33.2.3 Sending a Signal to a Thread
33.2.4 Dealing with Asynchronous Signals Sanely
33.3 Threads and Process Control
33.4 Thread Implementation Models
33.5 Linux Implementations of POSIX Threads
33.5.1 LinuxThreads
33.5.2 NPTL
33.5.3 Which Threading Implementation?
33.6 Advanced Features of the Pthreads API
33.7 Summary
33.8 Exercises

34 PROCESS GROUPS, SESSIONS, AND JOB CONTROL

35 PROCESS PRIORITIES AND SCHEDULING
35.2 Overview of Realtime Process Scheduling
35.4 CPU Affinity
35.5 Summary
35.6 Exercises

36 PROCESS RESOURCES
36.1 Process Resource Usage: getrusage()
36.2 Process Resource Limits: getrlimit() and setrlimit()
36.3 Details of Specific Resource Limits
36.4 Summary
36.5 Exercises

37 DAEMON 簡介、和建立
37.4 Using SIGHUP to Reinitialize a Daemon
使用 syslog 紀錄日誌
37.6 Summary
37.7 Exercise

38 WRITING SECURE PRIVILEGED PROGRAMS
38.1 Is a Set-User-ID or Set-Group-ID Program Required?
38.2 Operate with Least Privilege
38.3 Be Careful when Executing a Program
38.4 Avoid Exposing Sensitive Information
38.5 Confine the Process
38.6 Beware of Signals and Race Conditions
38.7 Pitfalls when Performing File Operations and File I/O
38.8 Don't Trust Inputs or the Environment
38.9 Beware of Buffer Overruns
38.10 Beware of Denial-of-Service Attacks
38.11 Check for Failures; Fail Safely
38.12 Summary
38.13 Exercises

39 CAPABILITIES
39.1 Rationale for Capabilities
39.2 The Linux Capabilities
39.3 Process and File Capabilities
39.3.1 Process Capabilities
39.3.2 File Capabilities
39.3.3 Purpose of the Process Permitted and Effective Capability Sets
39.3.4 Purpose of the File Permitted and Effective Capability Sets
39.3.5 Purpose of the Process and File Inheritable Sets
39.3.6 Assigning and Viewing File Capabilities from the Shell
39.4 The Modern Capabilities Implementation
39.5 Transformation of Process Capabilities During exec()
39.5.1 Capability Bounding Set
39.5.2 Preserving root Semantics
39.6 Effect on Process Capabilities of Changing User IDs
39.7 Changing Process Capabilities Programmatically
39.8 Creating Capabilities-Only Environments
39.9 Discovering the Capabilities Required by a Program
39.10 Older Kernels and Systems Without File Capabilities
39.11 Summary
39.12 Exercise

40 LOGIN ACCOUNTING
40.1 Overview of the utmp and wtmp Files
40.2 The utmpx API
40.3 The utmpx Structure
40.4 Retrieving Information from the utmp and wtmp Files
40.5 Retrieving the Login Name: getlogin()
40.6 Updating the utmp and wtmp Files for a Login Session
40.7 The lastlog File
40.8 Summary
40.9 Exercises

41 FUNDAMENTALS OF SHARED LIBRARIES
41.1 Object Libraries
41.2 Static Libraries
41.3 Overview of Shared Libraries
41.4 Creating and Using Shared Libraries—A First Pass
41.4.1 Creating a Shared Library
41.4.2 Position-Independent Code
41.4.3 Using a Shared Library
41.4.4 The Shared Library Soname
41.5 Useful Tools for Working with Shared Libraries
41.6 Shared Library Versions and Naming Conventions
41.7 Installing Shared Libraries
41.8 Compatible Versus Incompatible Libraries
41.9 Upgrading Shared Libraries
41.10 Specifying Library Search Directories in an Object File
41.11 Finding Shared Libraries at Run Time
41.12 Run-Time Symbol Resolution
41.13 Using a Static Library Instead of a Shared Library
41.14 Summary
41.15 Exercise

42 ADVANCED FEATURES OF SHARED LIBRARIES
42.1 Dynamically Loaded Libraries
42.1.1 Opening a Shared Library
42.1.2 Diagnosing Errors from the dlopen API
42.1.3 Obtaining the Address of a Symbol: dlsym()
42.1.4 Closing a Shared Library: dlclose()
42.1.5 Obtaining Information About Loaded Symbols: dladdr()
42.1.6 Accessing Symbols in the Main Program
42.2 Controlling Symbol Visibility
42.3 Linker Version Scripts
42.3.1 Controlling Symbol Visibility with Version Scripts
42.3.2 Symbol Versioning
42.4 Initialization and Finalization Functions
42.5 Preloading Shared Libraries
42.6 Monitoring the Dynamic Linker: LD_DEBUG
42.7 Summary
42.8 Exercises

43 INTERPROCESS COMMUNICATION OVERVIEW
43.1 A Taxonomy of IPC Facilities
43.2 Communication Facilities
43.3 Synchronization Facilities
43.4 Comparing IPC Facilities
43.5 Summary
43.6 Exercises

44 PIPES AND FIFOS
44.1 Overview
44.2 Creating and Using Pipes
44.3 Pipes As a Method of Process Synchronization
44.4 Using Pipes to Connect Filters
44.5 Talking to a Shell Command via a Pipe: popen() and pclose()
44.6 Pipes and stdio Buffering
44.7 FIFOs
44.8 A Client-Server Application Using FIFOs
44.9 Nonblocking I/O
44.10 Semantics of read() and write() on Pipes and FIFOs
44.11 Summary
44.12 Exercises

45 INTRODUCTION TO SYSTEM V IPC
45.1 API Overview
45.2 IPC Keys
45.3 Associated Data Structure and Object Permissions
45.4 IPC Identifiers and Client-Server Applications
45.5 Algorithm Employed by System V IPC get Calls
45.6 The ipcs and ipcrm Commands
45.7 Obtaining a List of All IPC Objects
45.8 IPC Limits
45.9 Summary
45.10 Exercises

46 SYSTEM V MESSAGE QUEUES
46.1 Creating or Opening a Message Queue: msgget()
46.2 Exchanging Messages
46.2.1 Sending Messages: msgsnd()
46.2.2 Receiving Messages: msgrcv()
46.3 Message Queue Control Operations: msgctl()
46.4 Message Queue Associated Data Structure
46.5 Message Queue Limits
46.6 Displaying All Message Queues on the System
46.7 Client-Server Programming with Message Queues
46.8 A File-Server Application Using Message Queues
46.9 Disadvantages of System V Message Queues
46.10 Summary
46.11 Exercises

47 SYSTEM V SEMAPHORES
47.1 Overview
47.2 Creating or Opening a Semaphore Set: semget()
47.3 Semaphore Control Operations: semctl()
47.4 Semaphore Associated Data Structure
47.5 Semaphore Initialization
47.6 Semaphore Operations: semop()
47.7 Handling of Multiple Blocked Semaphore Operations
47.8 Semaphore Undo Values
47.9 Implementing a Binary Semaphores Protocol
47.10 Semaphore Limits
47.11 Disadvantages of System V Semaphores
47.12 Summary
47.13 Exercises

48 SYSTEM V SHARED MEMORY
48.1 Overview
48.2 Creating or Opening a Shared Memory Segment: shmget()
48.3 Using Shared Memory: shmat() and shmdt()
48.4 Example: Transferring Data Via Shared Memory
48.5 Location of Shared Memory Segments in Virtual Memory
48.6 Storing Pointers in Shared Memory
48.7 Shared Memory Control Operations: shmctl()
48.8 Shared Memory Associated Data Structure
48.9 Shared Memory Limits
48.10 Summary
48.11 Exercises

49 MEMORY MAPPINGS
49.1 Overview
49.2 Creating a Mapping: mmap()
49.3 Unmapping a Mapped Region: munmap()
49.4 File Mappings
49.4.1 Private File Mappings
49.4.2 Shared File Mappings
49.4.3 Boundary Cases
49.4.4 Memory Protection and File Access Mode Interactions
49.5 Synchronizing a Mapped Region: msync()
49.6 Additional mmap() Flags
49.7 Anonymous Mappings
49.8 Remapping a Mapped Region: mremap()
49.9 The MAP_NORESERVE Flag and Swap Space Overcommitting
49.10 The MAP_FIXED Flag
49.11 Nonlinear Mappings: remap_file_pages()
49.12 Summary
49.13 Exercises

50 VIRTUAL MEMORY OPERATIONS
50.1 Changing Memory Protection: mprotect()
50.2 Memory Locking: mlock() and mlockall()
50.3 Determining Memory Residence: mincore()
50.4 Advising Future Memory Usage Patterns: madvise()
50.5 Summary
50.6 Exercises

51 INTRODUCTION TO POSIX IPC
51.1 API Overview
51.2 Comparison of System V IPC and POSIX IPC
51.3 Summary

52 POSIX MESSAGE QUEUES
52.1 Overview
52.2 Opening, Closing, and Unlinking a Message Queue
52.3 Relationship Between Descriptors and Message Queues
52.4 Message Queue Attributes
52.5 Exchanging Messages
52.5.1 Sending Messages: mq_send()
52.5.2 Receiving Messages: mq_receive()
52.5.3 Sending and Receiving Messages with a Timeout
52.6 Message Notification
52.6.1 Receiving Notification via a Signal
52.6.2 Receiving Notification via a Thread
52.7 Linux-Specific Features
52.8 Message Queue Limits
52.9 Comparison of POSIX and System V Message Queues
52.10 Summary
52.11 Exercises

53 POSIX SEMAPHORES
53.1 Overview
53.2 Named Semaphores
53.2.1 Opening a Named Semaphore
53.2.2 Closing a Semaphore
53.2.3 Removing a Named Semaphore
53.3 Semaphore Operations
53.3.1 Waiting on a Semaphore
53.3.2 Posting a Semaphore
53.3.3 Retrieving the Current Value of a Semaphore
53.4 Unnamed Semaphores
53.4.1 Initializing an Unnamed Semaphore
53.4.2 Destroying an Unnamed Semaphore
53.5 Comparisons with Other Synchronization Techniques
53.6 Semaphore Limits
53.7 Summary
53.8 Exercises

54 POSIX SHARED MEMORY
54.1 Overview
54.2 Creating Shared Memory Objects: shm_open()
54.3 Using Shared Memory Objects
54.4 Removing Shared Memory Objects: shm_unlink()
54.5 Comparisons Between Shared Memory APIs
54.6 Summary
54.7 Exercise

55 FILE LOCKING
55.1 Overview
55.2 File Locking with flock()
55.2.1 Semantics of Lock Inheritance and Release
55.2.2 Limitations of flock()
55.3 Record Locking with fcntl()
55.3.1 Deadlock
55.3.2 Example: An Interactive Locking Program
55.3.3 Example: A Library of Locking Functions
55.3.4 Lock Limits and Performance
55.3.5 Semantics of Lock Inheritance and Release
55.3.6 Lock Starvation and Priority of Queued Lock Requests
55.4 Mandatory Locking
55.5 The /proc/locks File
55.6 Running Just One Instance of a Program
55.7 Older Locking Techniques
55.8 Summary
55.9 Exercises
延伸閱讀:Linux 防止 Shell 指令稿重複執行教學

56 SOCKETS: INTRODUCTION
57 SOCKETS: UNIX DOMAIN
58 SOCKETS: FUNDAMENTALS OF TCP/IP NETWORKS
59 SOCKETS: INTERNET DOMAINS
60 SOCKETS: SERVER DESIGN
61 SOCKETS: ADVANCED TOPICS

62 TERMINALS

63 ALTERNATIVE I/O MODELS
63.1 Overview
63.1.1 Level-Triggered and Edge-Triggered Notification
63.1.2 Employing Nonblocking I/O with Alternative I/O Models
63.2 I/O Multiplexing
63.2.1 The select() System Call
63.2.2 The poll() System Call
63.2.3 When Is a File Descriptor Ready?
63.2.4 Comparison of select() and poll()
63.2.5 Problems with select() and poll()
63.3 Signal-Driven I/O
63.3.1 When Is "I/O Possible" Signaled?
63.3.2 Refining the Use of Signal-Driven I/O
63.4 The epoll API
63.4.1 Creating an epoll Instance: epoll_create()
63.4.2 Modifying the epoll Interest List: epoll_ctl()
63.4.3 Waiting for Events: epoll_wait()
63.4.4 A Closer Look at epoll Semantics
63.4.5 Performance of epoll Versus I/O Multiplexing
63.4.6 Edge-Triggered Notification
63.5 Waiting on Signals and File Descriptors
63.5.1 The pselect() System Call
63.5.2 The Self-Pipe Trick
63.6 Summary
63.7 Exercises

64 PSEUDOTERMINALS
64.1 Overview
64.2 UNIX 98 Pseudoterminals
64.2.1 Opening an Unused Master: posix_openpt()
64.2.2 Changing Slave Ownership and Permissions: grantpt()
64.2.3 Unlocking the Slave: unlockpt()
64.2.4 Obtaining the Name of the Slave: ptsname()
64.3 Opening a Pseudoterminal Master: ptyMasterOpen()
64.4 Connecting Two Processes with a Pseudoterminal: ptyFork()
64.5 Pseudoterminal I/O
64.6 Implementing script(1)
64.7 Terminal Attributes and Window Size
64.8 BSD Pseudoterminals
64.9 Summary
64.10 Exercises

A TRACING SYSTEM CALLS
B PARSING COMMAND-LINE OPTIONS
C CASTING THE NULL POINTER
D KERNEL CONFIGURATION
E FURTHER SOURCES OF INFORMATION
F SOLUTIONS TO SELECTED EXERCISES
BIBLIOGRAPHY
INDEX

2018年7月4日 星期三

滑鼠及微動開關

今天換滑鼠左鍵微動開關,做個紀錄。

滑鼠建議買 DPI 1000 以上的
微動開關
  • OMRON D2F-01F (日製)
    • D2F 是 OMRON 的長效系列
    • 帶有 01 字樣的使用金合金接點,耐用度10萬次 。沒有01字樣的使用銀合金接點,耐用度3萬次。
    • 帶有 F 字樣的,最大力量為 0.74N,按鍵較輕 。沒有的,最大力量為 1.47N,按鍵較重。
    • 另外有輕手感特製版 60gf(max)
  • asus rog sica
  • D2FC-F-7N(20M)、D2FC-F-7N(10M)
  • Zippy DF3-P1 (0.1A, 5VDC, 台製)
  • Zippy DF3-S3 (3A 125VAC 及 3A 250VAC)

滑鼠:建議買 DPI 1000 以上的,拆卸不用移除滑鼠腳。藍光?

  • ***logitech M105 還不錯,拆卸不用移除滑鼠腳。100.6x60.6x33.5 73g 1.5米
  • 華碩 U2000 滑鼠鍵盤組 滑鼠 1000 dpi
  • 公司 ASUS 滑鼠
    • 20190131 右鍵換 DF3-P1
    • 20200526 左鍵換舊滑鼠左鍵
    • 20200824 左鍵換 DF3-P1
    • 20221111 左鍵長按會斷換舊的 D2FC-F-7N
    • 20221122 左鍵長按會斷換舊品
  • Logitech M110 Silent (M110s, 型號 M-U0051):1000dpi、靜音 112.96 公釐 x 61.7 公釐 x 38.4 公釐 85 公克 線長 180 公分
    • 20200121 購買
    • 202202 左鍵換舊 G102 滾輪雙腳微動開關。原本紅頭雙腳可能是 KAILH 靜音微動
    • 202211 右鍵長沒反應,打算淘汰,左鍵、中鍵備品。
  • Logitech M100r:1000dpi、113x 62x38 90g 1.8米
    • https://home.gamer.com.tw/creationDetail.php?sn=2860998
  • ASUS A43
  • Logitech G402:謙 202202 購買
  • Logitech G90
    • 2019/11 購買
    • 2020/04 左鍵出問題送修,送回 G102。
    • 2021/? 左鍵出問題。左右 D2FC-F-7N(10M),滾輪雙腳,中間、左前、左後 Kailh
  • Logitech M90 400dpi:鼠體有點大、噪音有點大
    • 202004 右鍵故障淘汰,左鍵中鍵拆下當零件。

其它

  • 鐵氟龍膠帶
  • 3M 接點復活劑、接點復活膏
  • 光學滑鼠使用光學圖像處理晶片來偵測移動,通常使用紅色 LED,在太過平滑的平面上操作容易造成飄移的情況。雷射滑鼠則使用雷射光,基本上只要是在可以反射的平面上都可以使用,但比較敏感。藍光滑鼠最適用於各種平面上,但?精準度較差。觸控滑鼠:就是利用觸控來使用的,所以沒有滾輪。
  • 軌跡球滑鼠:拇指、食指、中指,空中。
  • 空中飛鼠

參考:

2018年6月2日 星期六

Official OpenWrt on BeagleBone Black

The official OpenWrt can work on BeagleBone Black. Either the master branch or the openwrt-18.06 branch.

Step 1

git clone https://git.openwrt.org/openwrt/openwrt.git
cd openwrt
make
When the menu appears, select "Target System" as (TI OMAP3/4/AM33xx), "Target Profile" as (TI AM335x BeagleBone Black), then < Exit >, < Yes > to save the configurations.

It takes time to compile ...

Step 2

After the compiling is completed, write the image into a µSD card. Assume /dev/sdb is the target µSD card.
zcat bin/targets/omap/generic/openwrt-omap-am335x-boneblack-ext4-sdcard.img.gz | sudo dd of=/dev/sdb bs=4096 conv=fsync

Step 3

Connect J1 console and plug the µSD card into BeagleBone Black. Apply power with S2 BOOT button pressed to boot from the µSD card.

To support BeagleBone Green

BeagleBone Green needs am335x-bonegreen.dtb and we can find it at
build_dir/target-arm_cortex-a8+vfpv3_musl_eabi/linux-omap/linux-4.14.43/arch/arm/boot/dts/am335x-bonegreen.dtb
Copy am335x-bonegreen.dtb into the dtbs directory in FAT partition of the µSD card. Step 3 again.

GPIO Output Control


Reference BeagleBone Black  pin mux which pin to use and find the 'GPIO No.' Here take P8 pin 35 as example, the GPIO No. is 8.
In the console, execute,
echo 8 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio8/direction
to set as output. Then,
echo 1 > /sys/class/gpio/gpio81/value
echo 0 > /sys/class/gpio/gpio81/value
to control output high or low.

USB Gadget

make kernel_menuconfig
        Device Drivers  --->
    [*] USB support  --->
    <*>   USB Gadget Support  --->
    <*>   USB Gadget precomposed configurations (Ethernet Gadget (with CDC Ethernet support))

2018年4月3日 星期二

Q.931 Channel Identification

Q.931 Channel Identification (ITU Q.931 section 4.5.13)
87654321Octet
IE ID: 0x18 1
Length2
ext.
1
Int. id.
present
Int. type0Pref./Excl.D-channel
ind
Info. channel
selection
3
ext.
0/1
Interface identifier3.1
ext.
1
Coding StandardNumber/
Map
Channel type/Map element type3.2
Channel number/Slot map3.3
  • interface identifier present 有設 => 有 octet 3.1 Interface identifier,可以有多個 byte,放界面的編號。
  • interface type= 0 表示 BRI,此時沒有 3.2 及 3.3,用 information channel selection 表示用哪個通道:00 = No channel, 01 = B1 channel, 10 = B2 channel
  • Preferred/Exclusive:0 = 偏好所選的通道 (也就是可以選別的)。1 = 排除眾議,就是要所選的通道。
  • D-channel Indicator:1 = 指 D-channel,忽略 Information Channel Selection。0 = 不是 D-channel。
  • Information Channel Selection
  • Coding Standard:0 = ITU-T 標準
  • Number/Map:0 = 用編號 (Channel number),1 = 用 bit map (Slot map)。
  • Element type:3 = B-channel
  • Channel number:MSB = 1 表示最後 byte,剩下 7-bit 為 channel 編號。
範例
0x18 0x01 0x81:BRI 偏好 B1 channel
0x18 0x03 0xA1 0x83 0x83:PRI 偏好 B channel 3

2018年3月22日 星期四

ATH-AR3BT

指示燈
  • 紅藍閃爍
  • 紅燈慢閃
  • 藍燈慢閃
  • 紅燈閃爍:電量不足,會發出 2 次嗶嗶聲。
  • 紅燈:micro USB 充電,藍牙連線會中止
  • 藍燈:充滿約 5 小時,可聽 30 小時
藍牙配對
  • v4.1
  • A2DP、AVRCP、HFP、HSP
  • AAC, AptX 編碼
  • NFC
耳罩
  • Ø40mm 驅動單元
  • 可折疊

內建麥克風
音樂播放或接聽來電等功能操作。
立體聲插座,電力耗盡可用有線方式聽。
190g

https://eu.audio-technica.com/resources/ATH/ATH-AR3BT_UM_V2_132312851_10L_web_170210.pdf

2017/08/28 NT$3450-648
其它
智慧型手機用附麥克風導線 AT338iS

SIP and ABNF

SIP 規範 RFC 3261 §25 提到 SIP 訊息格式用 ABNF 描述。ABNF (Augmented Backus–Naur Form, 擴充巴科斯範式, RFC 2234RFC 4234RFC 5234) 改良自 BNF (Backus–Naur Form),是一種用來描述通訊協定中一系列數值格式的語言。

ABNF 規範是一些如下推導規則的集合,以 crlf 換行結束
rule = definition ;comment crlf
  • rule:規則名稱,不分大小寫,以字母開始
  • definition:規則定義,可能包含一個或多個規則名稱、或數值的組合。
  • comment:需要的話,「;」開始為註解。
為了便於觀看,每條規則靠左對齊。當一個規則需要多行時,第二行開始縮排。

規則最後解析成一串值,值可用「%」表示法,二進位前置「%b」、十進位前置「%d」、十六進位前置「%x」。多個值串接可用一個前置,後面好幾個數字用「.」連接。一串值也可以用類似 C 語言字串前後加「"」表示,但在 ABNF 的字串是不分大小寫的。如果要分大小寫需要使用「%」表示法。

定義中使用的 Operator,依照 Precedence 高低
  • Value Range Alternatives (範圍):%c##-##
  • Repetition (重複)
    • *Rule:Rule 重複 0 次以上,* 前後可分別加上數字表示最少及最多的重複次數。
    • nRule:n 是數字,重複 n 次
  • Sequence Group (群組):(Rule1 Rule2)
  • Optional Sequence (選擇性的):[RULE]
  • Concatenation (串接):Rule1 Rule2
  • Alternatives (或者):Rule1 / Rule2
  • Incremental Alternatives (新增或者):Rule1 =/ Rule2

基本規則

US ASCII coded 字元集定義在 ANSI X3.4-1986,等同於國際標準 ISO 646。
DIGIT=%x30-39; 0-9,數字
ALPHA=%x41-5A / %x61-7A; A-Z / a-z,英文字母
alphanum=ALPHA / DIGIT; 英文字母和數字
一些規則採自 RFC 2396 但更新為 RFC 2234 相容,包括:
reserved=";" / "/" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / ",";
unreserved=alphanum / mark
mark="-" / "_" / "." / "!" / "~" / "*" / "'" / "(" / ")";mark 意思?
escaped="%" HEXDIG HEXDIG
HEXDIG=DIGIT / "A" / "B" / "C" / "D" / "E" / "F";十六進位數字不分大小寫
LHEX=DIGIT / %x61-66;十六進位數字限制小寫。
ASCII 中的可列印字元,除了 reserved (10 字元)、unreserved (71 字元)、%、和 SP 外,剩下 "#[\]^`{|}<> 12 字元。
SWS 是選擇性的 LWS,一般用在 token 和 separators 間。
LF   = %x0A              ;linefeed
CR   = %x0D              ;carriage return
CRLF = CR LF             ;換行

HTAB = %x09              ;horizontal tab
SP   = %x20
WSP  = SP / HTAB         ;white space
LWS  = [*WSP CRLF] 1*WSP ;linear whitespace
                         ;方便拆行顯示,語意和一個 SP 一樣。
                         ;一個或連續 WSP,前面可有一個換行,換行前可有連續 WSP。
                         ;接收或轉送可取代為 SP (和 HTTP/1.1 行為一致)。
SWS  = [LWS]             ;sep whitespace,選擇性的 LWS。
信頭的名稱和值。 規則 TEXT-UTF8-TRIM 用在描述性的欄位內容,並不打算給訊息解析器解釋,字元來自 UTF-8 字元集,不能是「quoted-string」,其中開頭和結束 LWS 是無意義的。
TEXT-UTF8-TRIM  =  1*TEXT-UTF8char *(*LWS TEXT-UTF8char)
TEXT-UTF8char   =  %x21-7E / UTF8-NONASCII
UTF8-NONASCII   =  %xC0-DF 1UTF8-CONT /
                   %xE0-EF 2UTF8-CONT /
                   %xF0-F7 3UTF8-CONT /
                   %xF8-Fb 4UTF8-CONT /
                   %xFC-FD 5UTF8-CONT
UTF8-CONT       =  %x80-BF

TEXT-UTF8-TRIM 只在 LWS 使用 CRLF 作為折行,LWS 會換成一個 SP 來解釋。

註:HTTP 使用 ISO 8859-1 字元集,以 ASCII 為基礎,在空置的 0xA0-0xFF 加入 96 個字母及符號,藉以供使用附加符號的拉丁字母語言使用。

許多 SIP 欄位包含來自「token」的字元,用 LWS 或「separators 」分隔的字。除非特別提到,「token」是不分大小寫 (case-insensitive)。在參數值如需要用到這些分隔字元,必須在「quoted-string」裡面。「word」特別用在 Call-ID,可使用「token」和大部分分隔字元。
token       =  1*(alphanum / "-" / "." / "!" / "%" / "*"
               / "_" / "+" / "`" / "'" / "~" )
DQUOTE      =  %x22 ; " (Double Quote)
separators  =  "(" / ")" / "<" / ">" / "@" /
               "," / ";" / ":" / "\" / DQUOTE /
               "/" / "[" / "]" / "?" / "=" /
               "{" / "}" / SP / HTAB
word        =  1*(alphanum / "-" / "." / "!" / "%" / "*" /
               "_" / "+" / "`" / "'" / "~" /
               "(" / ")" / "<" / ">" /
               ":" / "\" / DQUOTE /
               "/" / "[" / "]" / "?" /
               "{" / "}" )
當分隔字元用在 token 間,這些字元前後常可以允許 whitespace:
STAR    =  SWS "*" SWS ; 星號
SLASH   =  SWS "/" SWS ; slash
EQUAL   =  SWS "=" SWS ; 等號
LPAREN  =  SWS "(" SWS ; 左括號, %x28
RPAREN  =  SWS ")" SWS ; 右括號, %x29
RAQUOT  =  ">" SWS     ; 左角括號
LAQUOT  =  SWS "<"     ; 右角括號
SEMI    =  SWS ";" SWS ; 分號
LDQUOT  =  SWS DQUOTE  ; 雙引號開始
RDQUOT  =  DQUOTE SWS  ; 雙引號結束

comment 的內容用 () 括號包起來,只用在少數 header 欄位值。
其它欄位,括號是參數值的一部分。
comment  =  LPAREN *(ctext / quoted-pair / comment) RPAREN
ctext    =  %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII
            / LWS ; 所有字元,除了左右括號和反斜線。
用雙引號 quoted 的文字串解析為單一字,裡面的雙引號和反斜線要 escaped。
quoted-string = SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE
qdtext        = LWS / %x21 / %x23-5B / %x5D-7E
                / UTF8-NONASCII ; 不含雙引號和反斜線。
backslash 字元 ("\") 只用在「quoted-string」和「comment 」作單字元 quoting 機制。為避免與折行和 header separation 衝突,CR 和 LF 不能用此機制 escaped。
註:HTTP/1.1 可以 escape CR 和 LF。
quoted-pair = "\" (%x00-09 / %x0B-0C
              / %x0E-7F) ; 不含 CR 和 LF
任何字元用在 message-body
OCTET = %x00-FF ; 8 bits of data
註:規則名稱雖然不分大小寫,特殊基本規則多用大寫。
alphanum
! ' * - . _ ~
unreservedtokenword
( )unreservedsepword
$ &reserved--
+reservedtokenword
, ; = @reservedsep-
/ : ?reservedsepword
" <> [] {} \-sepword
# ^ |---
% `-tokenword
SP, HTAB-sep-
  • unreserved 和 reserved 沒有重疊。在有些欄位,unreserved 會擴充,例如 user-unreserved (擴充只取自 reserved?)。word 包含全部 unreserved。
  • token 則不含 unreserved 的 (),但多了 % 和 `、及 reserved 中的 +。
  • token 和 separators 沒有重疊。

URI 格式

SIP-message = Request / Response ; SIP 訊息 只有兩種,Request 和 Response。
Request     = Request-Line *( message-header ) CRLF [ message-body ]
Response    = Status-Line *( message-header ) CRLF [ message-body ]

message-header  =  (Accept
                /  Accept-Encoding
                /  Accept-Language
                /  Alert-Info
                /  Allow
                /  Authentication-Info
                /  Authorization
                /  Call-ID
                /  Call-Info
                /  Contact
                /  Content-Disposition
                /  Content-Encoding
                /  Content-Language
                /  Content-Length
                /  Content-Type
                /  CSeq
                /  Date
                /  Error-Info
                /  Expires
                /  From
                /  In-Reply-To
                /  Max-Forwards
                /  MIME-Version
                /  Min-Expires
                /  Organization
                /  Priority
                /  Proxy-Authenticate
                /  Proxy-Authorization
                /  Proxy-Require
                /  Record-Route
                /  Reply-To
                /  Require
                /  Retry-After
                /  Route
                /  Server
                /  Subject
                /  Supported
                /  Timestamp
                /  To
                /  Unsupported
                /  User-Agent
                /  Via
                /  Warning
                /  WWW-Authenticate
                /  extension-header) CRLF

INVITEm           =  %x49.4E.56.49.54.45 ; INVITE in caps
ACKm              =  %x41.43.4B ; ACK in caps
OPTIONSm          =  %x4F.50.54.49.4F.4E.53 ; OPTIONS in caps
BYEm              =  %x42.59.45 ; BYE in caps
CANCELm           =  %x43.41.4E.43.45.4C ; CANCEL in caps
REGISTERm         =  %x52.45.47.49.53.54.45.52 ; REGISTER in caps
Method            =  INVITEm / ACKm / OPTIONSm / BYEm
                     / CANCELm / REGISTERm ; 以上是大寫的 method 名稱,實際上不分大小寫。
                     / extension-method
extension-method  =  token
Response          =  Status-Line
                     *( message-header )
                     CRLF
                     [ message-body ]

Accept         =  "Accept" HCOLON
                   [ accept-range *(COMMA accept-range) ]
accept-range   =  media-range *(SEMI accept-param)
media-range    =  ( "*/*"
                  / ( m-type SLASH "*" )
                  / ( m-type SLASH m-subtype )
                  ) *( SEMI m-parameter )
accept-param   =  ("q" EQUAL qvalue) / generic-param
qvalue         =  ( "0" [ "." 0*3DIGIT ] )
                  / ( "1" [ "." 0*3("0") ] )
generic-param  =  token [ EQUAL gen-value ]
gen-value      =  token / host / quoted-string

Accept-Encoding  =  "Accept-Encoding" HCOLON
                     [ encoding *(COMMA encoding) ]
encoding         =  codings *(SEMI accept-param)
codings          =  content-coding / "*"
content-coding   =  token

Accept-Language  =  "Accept-Language" HCOLON
                     [ language *(COMMA language) ]
language         =  language-range *(SEMI accept-param)
language-range   =  ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) / "*" )

Alert-Info   =  "Alert-Info" HCOLON alert-param *(COMMA alert-param)
alert-param  =  LAQUOT absoluteURI RAQUOT *( SEMI generic-param )

Allow  =  "Allow" HCOLON [Method *(COMMA Method)]

Authorization     =  "Authorization" HCOLON credentials
credentials       =  ("Digest" LWS digest-response)
                     / other-response
digest-response   =  dig-resp *(COMMA dig-resp)
dig-resp          =  username / realm / nonce / digest-uri
                      / dresponse / algorithm / cnonce
                      / opaque / message-qop
                      / nonce-count / auth-param
username          =  "username" EQUAL username-value
username-value    =  quoted-string
digest-uri        =  "uri" EQUAL LDQUOT digest-uri-value RDQUOT
digest-uri-value  =  request-uri ; Equal to request-uri as specified
                     by HTTP/1.1
message-qop       =  "qop" EQUAL qop-value
cnonce            =  "cnonce" EQUAL cnonce-value
cnonce-value      =  nonce-value
nonce-count       =  "nc" EQUAL nc-value
nc-value          =  8LHEX
dresponse         =  "response" EQUAL request-digest
request-digest    =  LDQUOT 32LHEX RDQUOT
auth-param        =  auth-param-name EQUAL
                     ( token / quoted-string )
auth-param-name   =  token

other-response    =  auth-scheme LWS auth-param
                     *(COMMA auth-param)
auth-scheme       =  token

Authentication-Info  =  "Authentication-Info" HCOLON ainfo
                        *(COMMA ainfo)
ainfo                =  nextnonce / message-qop
                         / response-auth / cnonce
                         / nonce-count
nextnonce            =  "nextnonce" EQUAL nonce-value
response-auth        =  "rspauth" EQUAL response-digest
response-digest      =  LDQUOT *LHEX RDQUOT

Call-ID  =  ( "Call-ID" / "i" ) HCOLON callid
callid   =  word [ "@" word ]

Call-Info   =  "Call-Info" HCOLON info *(COMMA info)
info        =  LAQUOT absoluteURI RAQUOT *( SEMI info-param)
info-param  =  ( "purpose" EQUAL ( "icon" / "info"
               / "card" / token ) ) / generic-param

delta-seconds      =  1*DIGIT

Content-Disposition   =  "Content-Disposition" HCOLON
                         disp-type *( SEMI disp-param )
disp-type             =  "render" / "session" / "icon" / "alert"
                         / disp-extension-token
disp-param            =  handling-param / generic-param
handling-param        =  "handling" EQUAL
                         ( "optional" / "required"
                         / other-handling )
other-handling        =  token

disp-extension-token  =  token

Content-Encoding  =  ( "Content-Encoding" / "e" ) HCOLON
                     content-coding *(COMMA content-coding)

Content-Language  =  "Content-Language" HCOLON
                     language-tag *(COMMA language-tag)
language-tag      =  primary-tag *( "-" subtag )
primary-tag       =  1*8ALPHA
subtag            =  1*8ALPHA

Content-Length  =  ( "Content-Length" / "l" ) HCOLON 1*DIGIT
Content-Type     =  ( "Content-Type" / "c" ) HCOLON media-type
media-type       =  m-type SLASH m-subtype *(SEMI m-parameter)
m-type           =  discrete-type / composite-type
discrete-type    =  "text" / "image" / "audio" / "video"
                    / "application" / extension-token
composite-type   =  "message" / "multipart" / extension-token
extension-token  =  ietf-token / x-token
ietf-token       =  token
x-token          =  "x-" token
m-subtype        =  extension-token / iana-token
iana-token       =  token

m-parameter      =  m-attribute EQUAL m-value
m-attribute      =  token
m-value          =  token / quoted-string

CSeq  =  "CSeq" HCOLON 1*DIGIT LWS Method

Date          =  "Date" HCOLON SIP-date
SIP-date      =  rfc1123-date
rfc1123-date  =  wkday "," SP date1 SP time SP "GMT"
date1         =  2DIGIT SP month SP 4DIGIT
                 ; day month year (e.g., 02 Jun 1982)
time          =  2DIGIT ":" 2DIGIT ":" 2DIGIT
                 ; 00:00:00 - 23:59:59
wkday         =  "Mon" / "Tue" / "Wed"
                 / "Thu" / "Fri" / "Sat" / "Sun"
month         =  "Jan" / "Feb" / "Mar" / "Apr"
                 / "May" / "Jun" / "Jul" / "Aug"
                 / "Sep" / "Oct" / "Nov" / "Dec"

Error-Info  =  "Error-Info" HCOLON error-uri *(COMMA error-uri)
error-uri   =  LAQUOT absoluteURI RAQUOT *( SEMI generic-param )

Expires     =  "Expires" HCOLON delta-seconds

In-Reply-To  =  "In-Reply-To" HCOLON callid *(COMMA callid)

Max-Forwards  =  "Max-Forwards" HCOLON 1*DIGIT

MIME-Version  =  "MIME-Version" HCOLON 1*DIGIT "." 1*DIGIT

Min-Expires  =  "Min-Expires" HCOLON delta-seconds

Organization  =  "Organization" HCOLON [TEXT-UTF8-TRIM]

Priority        =  "Priority" HCOLON priority-value
priority-value  =  "emergency" / "urgent" / "normal"
                   / "non-urgent" / other-priority
other-priority  =  token

Proxy-Authenticate  =  "Proxy-Authenticate" HCOLON challenge
challenge           =  ("Digest" LWS digest-cln *(COMMA digest-cln))

                       / other-challenge
other-challenge     =  auth-scheme LWS auth-param
                       *(COMMA auth-param)
digest-cln          =  realm / domain / nonce
                        / opaque / stale / algorithm
                        / qop-options / auth-param
realm               =  "realm" EQUAL realm-value
realm-value         =  quoted-string
domain              =  "domain" EQUAL LDQUOT URI
                       *( 1*SP URI ) RDQUOT
URI                 =  absoluteURI / abs-path
nonce               =  "nonce" EQUAL nonce-value
nonce-value         =  quoted-string
opaque              =  "opaque" EQUAL quoted-string
stale               =  "stale" EQUAL ( "true" / "false" )
algorithm           =  "algorithm" EQUAL ( "MD5" / "MD5-sess"
                       / token )
qop-options         =  "qop" EQUAL LDQUOT qop-value
                       *("," qop-value) RDQUOT
qop-value           =  "auth" / "auth-int" / token

Proxy-Authorization  =  "Proxy-Authorization" HCOLON credentials

Proxy-Require  =  "Proxy-Require" HCOLON option-tag
                  *(COMMA option-tag)
option-tag     =  token

Require       =  "Require" HCOLON option-tag *(COMMA option-tag)

Retry-After  =  "Retry-After" HCOLON delta-seconds
                [ comment ] *( SEMI retry-param )

retry-param  =  ("duration" EQUAL delta-seconds)
                / generic-param

Server           =  "Server" HCOLON server-val *(LWS server-val)
server-val       =  product / comment
product          =  token [SLASH product-version]
product-version  =  token

Subject  =  ( "Subject" / "s" ) HCOLON [TEXT-UTF8-TRIM]

Supported  =  ( "Supported" / "k" ) HCOLON
              [option-tag *(COMMA option-tag)]

Timestamp  =  "Timestamp" HCOLON 1*(DIGIT)
               [ "." *(DIGIT) ] [ LWS delay ]
delay      =  *(DIGIT) [ "." *(DIGIT) ]

Unsupported  =  "Unsupported" HCOLON option-tag *(COMMA option-tag)
User-Agent  =  "User-Agent" HCOLON server-val *(LWS server-val)

Via               =  ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
via-parm          =  sent-protocol LWS sent-by *( SEMI via-params )

ia-params        =  via-ttl / via-maddr
                     / via-received / via-branch
                     / via-extension
via-ttl           =  "ttl" EQUAL ttl
via-maddr         =  "maddr" EQUAL host
via-received      =  "received" EQUAL (IPv4address / IPv6address)
via-branch        =  "branch" EQUAL token
via-extension     =  generic-param
sent-protocol     =  protocol-name SLASH protocol-version
                     SLASH transport
protocol-name     =  "SIP" / token
protocol-version  =  token
transport         =  "UDP" / "TCP" / "TLS" / "SCTP"
                     / other-transport
sent-by           =  host [ COLON port ]
ttl               =  1*3DIGIT ; 0 to 255

Warning        =  "Warning" HCOLON warning-value *(COMMA warning-value)
warning-value  =  warn-code SP warn-agent SP warn-text
warn-code      =  3DIGIT
warn-agent     =  hostport / pseudonym
                  ;  the name or pseudonym of the server adding
                  ;  the Warning header, for use in debugging

arn-text      =  quoted-string
pseudonym      =  token

WWW-Authenticate  =  "WWW-Authenticate" HCOLON challenge

extension-header  =  header-name HCOLON header-value
header-name       =  token
header-value      =  *(TEXT-UTF8char / UTF8-CONT / LWS)
message-body  =  *OCTET ; 任何長度任何字元
Request-URI = SIP-URI / SIPS-URI / absoluteURI
absoluteURI = scheme ":" ( hier-part / opaque-part )
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  • Request-URI 較複雜一點,基本結構都會有「:」,之前的部份稱 scheme,之後依照 scheme 解釋。

Header 欄位

message-header = (Accept / Accept-Encoding / Accept-Language / Alert-Info / Allow / Authentication-Info / Authorization / Call-ID / Call-Info / Contact / Content-Disposition / Content-Encoding / Content-Language / Content-Length / Content-Type / CSeq / Date / Error-Info / Expires / From / In-Reply-To / Max-Forwards / MIME-Version / Min-Expires / Organization / Priority / Proxy-Authenticate / Proxy-Authorization / Proxy-Require / Record-Route / Reply-To / Require / Retry-After / Route / Server / Subject / Supported / Timestamp / To / Unsupported / User-Agent / Via / Warning / WWW-Authenticate / extension-header) CRLF
extension-header = header-name HCOLON header-value
  • 把各種 header 都列出來了,最終都有 CRLF。

ContactFromReply-To、和 To 的格式都是 name-addr 或 addr-spec 加上參數,另外 name-addr 也用在 Record-RouteRoute。 name-addr 含有用 angle bracket 包起來的 addr-spec,所以 addr-spec 可以看成是 name-addr 的簡化,只有在沒有 display-name 且 addr-spec 沒有 「,」、「?」、「;」時使用。「;」為了跟信頭參數的區別。

name-addr    = [ display-name ] LAQUOT addr-spec RAQUOT
display-name = *(token LWS)/ quoted-string
addr-spec    = SIP-URI / SIPS-URI / absoluteURI

angle bracket 前後可有 LWS

參考

  1. wikipedia: Augmented_Backus-Naur_Form擴充巴科斯範式
  2. RFC3966 The tel URI for Telephone Numbers obsolete RFC2806 URLs for Telephone Calls

SIP header Via

所有 SIP 訊息 都要有 Via,縮寫 v。一開始的 UAC 和後續途經的每個 proxy 都會疊加一個 Via 放傳送的位址,依序作為回應的路徑。 格式 sent-protocol sent-by [ ;branch= branch ][ ; 參數 ...] s...